TcpClient BeginRead/Send 线程安全吗?

发布于 08-28 00:11 字数 404 浏览 7 评论 0原文

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

或者我是否必须在从 BeginRead 回调的代码和发送的代码中 lock() 中的 TcpClient

另外,如果我通过以下方式关闭 TcpClient

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

我是否还必须在 TcpClient 上进行 lock()

Using a .NET TcpClient if I have called an asynchronous BeginRead() on the associated network stream can I still call Write() on that stream on another thread?

Or do I have to lock() the TcpClient in the code that is called back from the BeginRead and the code that does the send?

Also if I close the TcpClient with:

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

Do I have to lock() on the TcpClient as well?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如何视而不见2024-09-04 00:11:59

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

读写操作可以
同时执行在
NetworkStream 类的实例
无需同步。
只要有一个唯一的线程
对于写操作和一个
读取操作的唯一线程,
不会有交叉干扰
读线程和写线程之间没有
需要同步。

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

The read/write portions of the TcpClient are thread safe, as explained in the documentation for the NetworkStream class (which is what the TcpClient uses for its actual 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.

To do with the closing, if you close the TcpClient on one thread, but then try to read/write using it on another thread after it is closed, an exception will be thrown. You can either synchronise the threads before it is closed in order to prevent them using the TcpClient, or just catch and handle the exception (for example, you might exit the thread's executing loop).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文