Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any performance difference between Begin* and *Async for sockets in .NET?

My application needs to rapidly broadcast a message to a large number of clients (1000-s) and collect results.

I'm thinking whether to use the BeginSend/EndSend etc. families of functions, or to use the SendAsync family - is there any performance difference? What is their difference at all, except for the *Async family not requiring allocation of an IAsyncResult?

If I'm understanding correctly, they both use IO completion ports and the standard .net thread pool... So what's the difference?

like image 804
jkff Avatar asked Mar 05 '11 08:03

jkff


1 Answers

The difference is only in the pattern used.

SendAsync in facts use an Event-Based Pattern. BeginSend and EndSend use the IAsyncResult pattern.

EDIT: I don't know how the IAsyncResult interface is implemented in Socket class but here is a document from MSDN that explains when to implement one pattern or the other one.

Excerpt from the last part:

While the Event-based Asynchronous Pattern has many benefits under the previously mentioned scenarios, it does have some drawbacks, which you should be aware of if performance is your most important requirement.

There are three scenarios that the event-based pattern does not address as well as the IAsyncResult pattern:

  1. Blocking wait on one IAsyncResult

  2. Blocking wait on many IAsyncResult objects

  3. Polling for completion on the IAsyncResult

You can address these scenarios by using the event-based pattern, but doing so is more cumbersome than using the IAsyncResult pattern.

Developers often use the IAsyncResult pattern for services that typically have very high performance requirements. For example, the polling for completion scenario is a high-performance server technique.

Additionally, the event-based pattern is less efficient than the IAsyncResult pattern because it creates more objects, especially EventArgs, and because it synchronizes across threads.

The following list shows some recommendations to follow if you decide to use the IAsyncResult pattern:

  • Only expose the IAsyncResult pattern when you specifically require support for WaitHandle or IAsyncResult objects.

  • Only expose the IAsyncResult pattern when you have an existing API that uses the IAsyncResult pattern.

  • If you have an existing API based on the IAsyncResult pattern, consider also exposing the event-based pattern in your next release.

  • Only expose IAsyncResult pattern if you have high performance requirements which you have verified cannot be met by the event-based pattern but can be met by the IAsyncResult pattern.

like image 86
as-cii Avatar answered Sep 29 '22 11:09

as-cii