gpt4 book ai didi

c# - Stream.Write 是线程安全的吗?

转载 作者:太空狗 更新时间:2023-10-29 21:11:15 25 4
gpt4 key购买 nike

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

我的发送代码使用 BinaryWriter 将完整的“消息”写入底层 NetworkStream。 RPC 协议(protocol)还实现了一种心跳算法,其中 RPC 服务器每 15 秒发送一次 PING 消息。 ping 由单独的线程发送,因此,至少在理论上,可以在服务器正在将大量响应流回客户端时发送 ping。

假设我有一个 Send 方法如下,其中 stream 是一个 NetworkStream:

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();
}

所以我的问题是,是对 bw.Write 的调用(以及暗示对底层 StreamWrite 的调用> 方法)原子?也就是说,如果发送线程上仍在进行冗长的Write,并且心跳线程启动并发送 PING 消息,该线程是否会阻塞直到原始Write调用完成,还是我必须向 Send 方法添加显式同步以防止两个 Send 调用破坏流?

最佳答案

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

来自 Stream Class ,所以不能保证。

关于c# - Stream.Write 是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2407209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com