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?
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.
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 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.
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.
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:
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
):
socket.BeginConnect(host, port, asyncResult =>
{
socket.EndConnect(asyncResult);
Console.WriteLine("Socket connected");
}, null);
await Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, host, port, null);
Console.WriteLine("Socket connected");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With