Is TcpClient BeginRead / Send Stream Safe?

Using .NET TcpClient , if I called asynchronous BeginRead() on a connected network stream, can I still call Write() on this stream in another stream?

Or do I need TcpClient lock() in the code that is called from BeginRead and the code that sends?

Also, if I close TcpClient with:

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

Do I need lock() on TcpClient ?

+4
source share
1 answer

The TcpClient read / write TcpClient are thread safe, as described in the documentation for the NetworkStream class (which is used by TcpClient for its actual I / O):

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 write operations and one unique thread for read operations, there will be no crosstalk between read and write streams and no synchronization is required.

To close a close, if you close TcpClient in one thread, but then try to read / write using it in another thread after closing it, an exception will be thrown. You can either synchronize the threads before they are closed to prevent TcpClient from using TcpClient , or simply catch and handle the exception (for example, you can exit the thread's execution loop).

+8
source

Source: https://habr.com/ru/post/1306094/


All Articles