Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous socket operations in a Task

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?

like image 308
iguanaman Avatar asked Sep 12 '14 18:09

iguanaman


People also ask

What are asynchronous sockets?

In an asynchronous socket, you CAN do other stuff while waiting for the client to send data to you, so now you CAN have multiple clients connecting to you. Synchronous uses a function like receive() which blocks until it gets a message. Asynchronous has beginReceive() endReceive() or similar functions.

What is task in asynchronous?

Asynchronous tasks run in the background and evaluate functions asynchronously when there is an event. Asynchronous tasks may run only until some work is completed, or they may be designed to run indefinitely.

What is task in asynchronous programming?

What Is A Task In C#? A task in C# is used to implement Task-based Asynchronous Programming and was introduced with the . NET Framework 4. The Task object is typically executed asynchronously on a thread pool thread rather than synchronously on the main thread of the application.

What is the difference between synchronous sockets and asynchronous sockets?

The send, receive, and reply operations may be synchronous or asynchronous. A synchronous operation blocks a process till the operation completes. An asynchronous operation is non-blocking and only initiates the operation.


1 Answers

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");
like image 183
i3arnon Avatar answered Sep 30 '22 06:09

i3arnon