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?
The read/write portions of the
TcpClientare thread safe, as explained in the documentation for theNetworkStreamclass (which is what theTcpClientuses for its actual IO):To do with the closing, if you close the
TcpClienton 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).