Stream.WriteTo 锁定线程
我有这样的代码:
public static void SerializeRO(Stream stream, ReplicableObject ro) {
MemoryStream serializedObjectStream = new MemoryStream();
Formatter.Serialize(serializedObjectStream, ro);
MemoryStream writeStream = new MemoryStream();
BinaryWriter bw = new BinaryWriter(writeStream);
bw.Write(serializedObjectStream.Length);
serializedObjectStream.Seek(0, SeekOrigin.Begin);
serializedObjectStream.WriteTo(writeStream);
serializedObjectStream.Close();
writeStream.WriteTo(stream);
bw.Close();
}
writeStream.WriteTo(stream);
行永远不会完成。程序到达那条线并且不会继续进行。
stream
始终是 NetworkStream
。我已经检查过,我认为它是一个有效的对象(至少它不是 null
也不是已处置)。
那么到底是怎么回事呢?
I have this code:
public static void SerializeRO(Stream stream, ReplicableObject ro) {
MemoryStream serializedObjectStream = new MemoryStream();
Formatter.Serialize(serializedObjectStream, ro);
MemoryStream writeStream = new MemoryStream();
BinaryWriter bw = new BinaryWriter(writeStream);
bw.Write(serializedObjectStream.Length);
serializedObjectStream.Seek(0, SeekOrigin.Begin);
serializedObjectStream.WriteTo(writeStream);
serializedObjectStream.Close();
writeStream.WriteTo(stream);
bw.Close();
}
The line writeStream.WriteTo(stream);
never finishes. The program gets to that line and won't progress.
stream
is always a NetworkStream
. I've checked and I think it's a valid object (at least it's not null
nor disposed).
So what's going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我尝试了你的代码 - 写入
FileStream
- 并且我总是将零字节写入流。我不知道为什么当没有什么可写时WriteTo
会在NextWorkStream
上阻塞,但这可能是一个问题当我从
MemoryStream< 中提取字节时/code> 并直接编写它们以流式传输所有内容,例如(我正在例程中创建一个二进制格式化程序,看来您已经有了一个格式化程序)。
不过,我会用一个
MemoryStream
这样做,并直接写入stream
,除非有一些我不知道的NetworkStream
(这当然会关闭stream
这可能不是您想要的)不会关闭 NetworkStream 的版本(只是不要将二进制编写器放在 using 语句或
Close()它)
I tried your code - writing to a
FileStream
- and I always get zero bytes written to the stream. I don't know whyWriteTo
would block on aNextWorkStream
when there's nothing to write, but that could be a problemWhen I extract the bytes from the
MemoryStream
and write them directly to stream everything works e.g. (I'm creating a binary formatter in the routine, it seems you already have a formatter).However I'd do it like this with one
MemoryStream
and writing directly tostream
, unless there's something I don't know aboutNetworkStream
(this will of course closestream
which may not be what you want)Version that won't close your NetworkStream (just don't put the binary writer in a using statement or
Close()
it)只是我的想法:在将流写入另一个流之前,尝试关闭您的
BinaryWriter
。当您的写入器打开时,流尚未完成,因此WriteTo
newer 将找到流的末尾。Just my thoughts: try to close your
BinaryWriter
before writing stream to another. While your writer is opened stream is not finished and as the resultWriteTo
newer will find the end of the stream.