When to use async when working with TcpClients?

Possible duplicate:
Difference between NetworkStream.Read () and NetworkStream.BeginRead ()?

Diving into the TcpClient class is a bit, and I noticed that the TcpClient.GetStream () class has the Read() and BeginRead() and EndRead() .

Which one should I use? I understand that Begin and End functions are asynchronous functions, but should I use them? In what circumstances would I use Read for my asynchronous counterpart? How about recording?

I am currently just doing something like this:

 byte[] message = new byte[4096]; int bytesRead = clientStream.Read(message, 0, 4096); 

Should I use BeginRead and EndRead instead?

+4
source share
1 answer

Choosing between synchronous and asynchronous methods is essentially the choice for your application’s streaming model. Since for most applications it is unacceptable to be immune to the user when performing other tasks (for example, when accessing the network, as is the case), you need to provide a way to respond to user input during operation.

The two most common options for this are:

  • To make your application multithreaded, which allows it to simultaneously perform several operations.
  • Use asynchronous callbacks and handle work in small chunks when responding to a user between processing these fragments

The choice between, for example, Read and BeginRead corresponds to the choice between options 1 and 2 above (I believe that when using locking methods such as Read , you will need to do this in a different thread than the one on which your user interface is running, therefore while technically this is not necessary, in practice, an application that uses blocking calls will be multithreaded).

If you do not quite understand what I'm talking about, use synchronous calls, because it will be easier. You will have the opportunity to revise your approach later if (when) your application starts responding.

+3
source

All Articles