Stream.WriteTo锁定线程

时间:2011-09-01 18:20:22

标签: c# stream

我有这段代码:

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也不是处置)。

那是怎么回事?

2 个答案:

答案 0 :(得分:1)

我的想法是:在将流写入另一个之前尝试关闭BinaryWriter。当您的编写器打开时,流未完成,因此结果WriteTo更新将找到流的结尾。

答案 1 :(得分:1)

我尝试了你的代码 - 写入FileStream - 我总是将零字节写入流中。我不知道为什么WriteTo会阻止NextWorkStream当没有什么可写的时候,但这可能是个问题

当我从MemoryStream中提取字节并将它们直接写入流时,一切正常工作,例如(我在例程中创建了一个二进制格式化程序,看起来你已经有了格式化程序)。

public static void SerializeRO(Stream stream, object ro)
{
    MemoryStream serializedObjectStream = new MemoryStream();
    var f = new BinaryFormatter();
    f.Serialize(serializedObjectStream, ro);

    MemoryStream writeStream = new MemoryStream();
    BinaryWriter bw = new BinaryWriter(writeStream);

    var bytes = serializedObjectStream.ToArray();
    bw.Write(bytes.Length);
    bw.Write(bytes);

    var bwBytes = writeStream.ToArray();

    stream.Write(bwBytes, 0, bwBytes.Length);

    bw.Close();
}

但是我会用一个MemoryStream直接写stream这样做,除非我不知道有关NetworkStream的事情(这当然会关闭{{} 1}}这可能不是你想要的)

stream

不会关闭您的NetworkStream的版本(只是不要将二进制编写器放在using语句或public static void SerializeRO(Stream stream, object ro) { byte[] allBytes; using (var serializedObjectStream = new MemoryStream()) { var f = new BinaryFormatter(); f.Serialize(serializedObjectStream, ro); allBytes = serializedObjectStream.ToArray(); } using (var bw = new BinaryWriter(stream)) { bw.Write(allBytes.Length); bw.Write(allBytes); } } 中)

Close()