简体   繁体   English

C# StreamReader 与 NetworkStream 一起挂起

[英]C# StreamReader hangs with NetworkStream

So I've been messing with this code for awhile but couldn't figure out why it doesn't work (I called the Serialize method and Deserialize on two different threads in a while(true) loop, the Serialize thread keeps sending while the Deserialize method gets stuck)所以我一直在弄乱这段代码,但不知道为什么它不起作用(我在while(true)循环中调用了Serialize方法并在两个不同的线程上Deserialize序列化, Serialize线程一直在发送而Deserialize方法卡住了)

        public static void Serialize(NetworkStream stream, object obj)
        {
            StreamWriter writer = new StreamWriter(stream);
            Console.WriteLine("Start Writing");
            writer.WriteLine(Deconstructor.Deconstruct(obj));
            Console.WriteLine("Done Writing");
        }

        public static object Deserialize(NetworkStream stream)
        {
            StreamReader reader = new StreamReader(stream);
            Console.WriteLine("Start reading");
            string objGraphData = reader.ReadLine();
            Console.WriteLine("Done reading");
            return Constructor.Construct(objGraphData);
        }

OutPut: OutPut:

Accepting new socket!
Start reading
Start Writing
Done Writing
Start Writing
Done Writing
Start Writing
Done Writing
Start Writing
Done Writing
Start Writing
Done Writing
Start Writing
Done Writing
Start Writing
Done Writing

Note: The streams work as well (I've tested them before with a BinaryFormatter) but now when I use StreamWriter/StreamReader instead of a BinaryFormatter the StreamReader part hangs on the reader.ReadLine() part注意:流也可以正常工作(我之前使用 BinaryFormatter 测试过它们)但是现在当我使用 StreamWriter/StreamReader 而不是 BinaryFormatter 时,StreamReader 部分挂在 reader.ReadLine() 部分

The biggest problem here appears to be that you have a StreamReader (and writer) that is local to a single deserialize (or serialize) call.这里最大的问题似乎是您有一个StreamReader (和 writer),它位于单个反序列化(或序列化)调用的本地。 However, StreamReader and StreamWriter are stateful types that have their own local buffers (because you can't push data back into a Stream if you've read too much, and you don't want to read individual byte values, for performance reasons - so it reads a chunk and then decodes it over multiple calls).但是, StreamReaderStreamWriter是有状态的类型,它们有自己的本地缓冲区(因为如果你读得太多,你就不能将数据推回Stream ,并且你不想读取单个byte值,出于性能原因 -所以它读取一个块,然后通过多次调用对其进行解码)。

Because of this, once you've created a reader/writer over a Stream , you need to consider that reader/writer the single "owner" of that data.因此,一旦您通过Stream创建了读取器/写入器,您需要将该读取器/写入器视为该数据的单一“所有者”。 Effectively, only ever create one of each, and then don't talk directly to the stream again.实际上,只创建一个,然后不要再次直接与 stream 对话。 Retain the reader/writer, and pass the same reader/writer to multiple successive serialize/deserialize calls.保留读取器/写入器,并将相同的读取器/写入器传递给多个连续的序列化/反序列化调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM