开发者

When to using async when dealing with TcpClients? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Difference between NetworkStream.Read() and NetworkStream.BeginRead()?

Messing with the TcpClient class a bit and I noticed the TcpClient.GetStream() class has both Read() and BeginRead() and EndRead() functions.

Which of these should I use? I realize that the Begin and End functions are async functions but should I use them? Under what circumstances would I use Read versus its async counterpart? What about 开发者_如何学GoWrite?

Currently I am just doing something like this:

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

Should I be using BeginRead and EndRead instead?


The choice between the synchronous and async methods is in essence a choice for the threading model of your application. Since for most applications it is unacceptable to be unresponsive to the user while they perform other tasks (such as accessing the network, as is the case in question), you need to provide for a way to respond to user input while work is being done.

The two most widespread options for this are

  1. To make your application multithreaded, effectively allowing it to do more than one thing at the same time
  2. To use asynchronous callbacks and process work in small chunks while responding to the user between processing these chunks

The choice between e.g. Read and BeginRead corresponds to the choice between options 1 and 2 above (I assume that if using blocking methods such as Read you will need to do so on a different thread than the one your UI runs on, so while technically it is not necessary, in practice an application that uses blocking calls will be multithreaded).

If you do not fully understand what I 'm talking about, use the synchronous calls because it will be easier. You will have the opportunity to rethink your approach later, if (when) your application begins being unresponsive.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜