views:

357

answers:

1

Using a dotNET 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?

Thanks in advance.

+3  A: 

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 it's 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).

Kazar
Thank you I completely missed that in MSDN my bad - I apologise.On the close I am catching and handling the exception but just wasn't sure if that was dodgy so thanks for clarifying that is ok as that isn't documented as far as I can tell.
wb
Yeah, it's perfectly normal for it to throw an exception if you try to write to / read from a TcpClient that has been closed. You'll see that across all of the .NET socket APIs.
Kazar