Stream.Write是否是线程安全的?

Mik*_*oss 6 c# networking multithreading c#-2.0

我正在为传统的RPC实现开发一个客户端/服务器库,并且遇到了在等待接收到RPC请求消息的响应消息时客户端有时会挂起的问题.事实证明,真正的问题出在我的消息框架代码中(我从底层读取数据时没有正确处理消息边界NetworkStream),但它也让我怀疑我用来通过网络发送数据的代码,特别是RPC服务器作为客户端RPC请求的结果向客户端发送大量数据的情况.

我的发送代码使用a BinaryWriter向底层写一个完整的"消息" NetworkStream.RPC协议还实现了心跳算法,其中RPC服务器每15秒发送一次PING消息.ping是由一个单独的线程发出的,因此,至少在理论上,当服务器处于将大响应流回客户端时,可以发送ping.

假设我有一个Send如下方法,其中streamNetworkStream:

public void Send(Message message)
{
   //Write the message to a temporary stream so we can send it all-at-once
   MemoryStream tempStream = new MemoryStream();
   message.WriteToStream(tempStream);

   //Write the serialized message to the stream.
   //The BinaryWriter is a little redundant in this 
   //simplified example, but here because
   //the production code uses it.
   byte[] data = tempStream.ToArray();
   BinaryWriter bw = new BinaryWriter(stream);
   bw.Write(data, 0, data.Length);
   bw.Flush();
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,是呼叫bw.Write(和隐含调用底层StreamWrite方法)原子?也就是说,如果Write发送线程仍在进行冗长,并且心跳线程启动并发送PING消息,那么该线程是否会阻塞直到原始Write调用结束,或者我是否必须向该Send方法添加显式同步以防止Send破坏流的两个电话?

Adr*_*der 9

此类型的任何公共静态(在Visual Basic中为Shared)成员都是线程安全的.任何实例成员都不保证是线程安全的.

流类,所以没有它不能保证.