How to use async operation in IO-Bound with TaskCompletionSource?

137 views Asked by At

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;
}
1

There are 1 answers

2
Tomas Tomov On

You can use Task.Run(() => action()), but under the hood it will delegate it to the ThreadPool. And also the ThreadPool will not necessarily create a brand new Thread, it usually has some threads that are being reused.