TcpClient BeginRead/Send 线程安全吗?
使用 .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?
TcpClient
的读/写部分是线程安全的,如NetworkStream
类的文档中所述(这是TcpClient
使用的)其实际IO):为了进行关闭,如果您在一个线程上关闭
TcpClient
,但在关闭后尝试在另一个线程上使用它进行读/写操作,则会引发异常。您可以在线程关闭之前同步线程,以防止它们使用TcpClient
,或者只是捕获并处理异常(例如,您可能会退出线程的执行循环)。The read/write portions of the
TcpClient
are thread safe, as explained in the documentation for theNetworkStream
class (which is what theTcpClient
uses for its actual IO):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 theTcpClient
, or just catch and handle the exception (for example, you might exit the thread's executing loop).