开发者

What's the difference between BeginConnect and ConnectAsync?

What is the difference between BeginConnect and ConnectAsync? Subsequently, what is the difference between BeginDisconnect and DisconnectAsync?

The ConnectAsync documentation states:

"Begins an asynchronous request for a remote hos开发者_如何转开发t connection."

The BeginConnect documentation also states:

"Begins an asynchronous request for a remote host connection."

Both the DisconnectAsync and BeginDisconnect also state the same thing:

"Begins an asynchronous request to disconnect from a remote endpoint."

What's the difference between those method pairs and which one should be used?


Socket.ConnectAsync provides SocketAsyncEventArgs as a parameters which contains a lot more information compared to 3 params provided by BeginConnect. Also I know that ConnectAsync introduced later than BeginConnect and solves some issues related to timeouts (cannot remember the source of this discussion now). Prefer ConnectAsync when possible (though it requires min .NET 2.0 SP1).

There is a catch with ConnectAsync about the callbacks. If this is of concern, here are the discussions about it: Stack overflow when using the System.Net.Sockets.Socket.AcceptAsync model and AsyncCallBack CompletedSynchronously

There is no support for BeginConnect method in Silverlight (only ConnectAsync is supported) so that may be another concern if you intend to develop client side Silverlight applications.

Also the patterns used in two approaches are different. Here is the discussion: Is there any performance difference between Begin* and *Async for sockets in .NET?


The XXXXAsync methods were introduced because they reduce the amount of memory thrashing that occurs when servers have many connected clients. Coupled with pooling described in the docs, using this API considerably reduces the amount of work GC has to perform when compared to the older BeginXXX API.

The docs say the following:

The main feature of these enhancements is the avoidance of the repeated allocation and synchronization of objects during high-volume asynchronous socket I/O. The Begin/End design pattern currently implemented by the System.Net.Sockets.Socket class requires a System.IAsyncResult object be allocated for each asynchronous socket operation.

So, unless you're writing a server for many thousands of connected clients, I wouldn't bother with XXXXAsync. The API is considerably harder to implement and of little gain to anything other than enterprise level services.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜