Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 host 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?

like image 354
Kiril Avatar asked Apr 23 '11 15:04

Kiril


2 Answers

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?

like image 183
Teoman Soygul Avatar answered Nov 08 '22 06:11

Teoman Soygul


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.

like image 12
spender Avatar answered Nov 08 '22 06:11

spender