Asynchronous socket operations in a Task

余生颓废 提交于 2020-11-30 04:49:54

问题


I have a Threading.Tasks.Task that handles a number of client socket operations (connecting, receiving and sending).

I understand that where possible it's best to use non blocking methods using Await because otherwise I'll end up with "parked threads waiting for their response". However, while the Socket class has async methods (SendAsync and so on) they aren't the same as the usual Task Parallel Library async methods, they don't return a Task and cannot be awaited.

I realise that I can wrap these socket async methods with a TaskCompletionSource but is there any benefit to doing so or will it ultimately still be parking the thread?


回答1:


As Servy explained. Using TaskCompletionSource as in of itself doesn't create (or park) any threads as long as you're using the asynchronous pattern correctly.

There are 3 different asynchronous patterns in the .Net framework:

  1. Asynchronous Programming Model (APM).
  2. Event-based Asynchronous Pattern (EAP).
  3. Task-based Asynchronous Pattern (TAP).

What you're trying to achieve is "convert" one pattern, the EAP, to another one, TAP. A simpler solution would be to use .Net's built-in "conversion" from the APM pattern to TAP, Task.Factory.FromAsync (which internally uses TaskCompletionSource):

APM

socket.BeginConnect(host, port, asyncResult =>
{
    socket.EndConnect(asyncResult);
    Console.WriteLine("Socket connected");
}, null);

TAP

await Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, host, port, null);
Console.WriteLine("Socket connected");



回答2:


Translating a non-Task based asynchronous model to a task based asyncrhonous model through the use of a TaskCompletionSource does not create any new threads, no. It simply allows you to use a different syntax for interacting with that asynchronous operation.

It's not objectively better or worse, it's simply a different syntax for doing the same thing. Subjectively the task based model tend to be easier to use, but the whole design of both models means that they end up doing the same functional thing, assuming each is used properly.



来源:https://stackoverflow.com/questions/25814575/asynchronous-socket-operations-in-a-task

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