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

后端 未结 1 581
夕颜
夕颜 2020-12-29 06:44

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/End

相关标签:
1条回答
  • 2020-12-29 07:03

    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.

    0 讨论(0)
提交回复
热议问题