I want to implement an asynchronous mechanism in IO-Bound, and how can I implement this with TaskCompletionSource without consuming a new thread?
This following sample to create new thread in thread pool, but I am looking for a new approach by TaskCompletionSource without create new thread in thread pool?!
public static Task RunAsync(Action action)
{
var tcs = new TaskCompletionSource<Object>(TaskCreationOptions.RunContinuationsAsynchronously);
ThreadPool.QueueUserWorkItem(_ =>
{
try
{
action();
tcs.SetResult(null);
}
catch(Exception exc) { tcs.SetException(exc); }
});
return tcs.Task;
}
You can use
Task.Run(() => action())
, but under the hood it will delegate it to theThreadPool
. And also theThreadPool
will not necessarily create a brand newThread
, it usually has some threads that are being reused.