What's the difference between BeginConnect and ConnectAsync?

倾然丶 夕夏残阳落幕 提交于 2019-11-27 13:07:55
Teoman Soygul

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!