c# - TcpClient BeginRead/Send 线程安全吗?

标签 c# .net thread-safety tcpclient networkstream

使用 .NET TcpClient 如果我在关联的网络流上调用了异步 BeginRead(),我仍然可以调用 Write()在另一个线程的那个流上?

或者我是否必须 lock()BeginRead 回调的代码中的 TcpClient 以及执行发送?

此外,如果我关闭 TcpClient :

client.GetStream().Close();
client.Close();

我是否也必须在 TcpClient 上使用 lock()

最佳答案

TcpClient 的读/写部分是线程安全的,如 NetworkStream 类的文档中所述(TcpClient 用于其实际的 IO):

Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization. As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required.

关于关闭,如果您在一个线程上关闭了TcpClient,但在关闭后尝试在另一个线程上使用它进行读/写,则会抛出异常。您可以在线程关闭之前同步线程以防止它们使用 TcpClient,或者只捕获并处理异常(例如,您可以退出线程的执行循环)。

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

相关文章:

c++ - QList、QVector 或 std::vector 多线程使用

c++ - 线程安全堆栈互斥体在忙碌时被销毁

java - 使用 final 参数是否会阻止类成为线程安全的?

c# - 在 C# 中的类中添加否定运算符 (?)

c# - 将从 ToString ("MMMM") 返回的月份名称更改为自己的名称

c# - 正确填充多维数组

c# - 将 List<string> 转换为 StringCollection

c# - 以渐进格式保存 JPEG

javascript - 如何将 HttpResponseMessage 的 ByteArrayContent 下载为 zip

c# - XPathNavigator 是否需要 MoveToParent()/MoveToFirstChild() 对?