Asynchronous socket operations in a task
I have a Threading.Tasks.Task that handles multiple client socket operations (connect, receive and send).
I understand that it is better to use non-blocking methods using Await whenever possible, because otherwise I will end up with "parked threads waiting for their response". However, while the Socket class has asynchronous methods (SendAsync, etc.), they are not the same as normal async methods for a parallel task library, they do not return a task, and cannot be expected.
I understand that I can wrap these async socket methods with a TaskCompletionSource, but is there any benefit to doing this or will it still end up threading it eventually?
source to share
As Servy explained. Usage TaskCompletionSource
as it does not by itself create (or park) any threads if you use the async pattern correctly.
There are 3 different asynchronous patterns in the .Net framework:
- Asynchronous Programming Model (APM) .
- Event-Based Asynchronous Pattern (EAP) .
- Task Based Asynchronous Pattern (TAP) .
What you are trying to achieve is "convert" one template, EAP, to another, TAP. A simpler solution would be to use the built-in .NET "transform" from the APM to TAP pattern, 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");
source to share
Converting a task-based asynchronous model to a task-based asynchronous model using TaskCompletionSource
doesn't create any new threads, no. It just allows you to use a different syntax to interact with this asynchronous operation.
It's not objectively better or worse, it's just a different syntax for doing the same thing. Subjectively, the task-based model is easier to use, but the whole design of both models means that they end up doing the same functional thing, assuming that each is used appropriately.
source to share