1

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
    What is action? It heavily depends on the underlying implementation of action, and is not something that you can just transparently transform without consuming a thread. – user1937198 Apr 13 '21 at 11:38

1 Answers1

1

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.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • How this will differ from `ThreadPool.QueueUserWorkItem` which should reuse threads from `ThreadPool` also? I highly suspect that OP wants somehow to perform IO-bound operation without consuming thread while waiting for response. – Guru Stron Apr 13 '21 at 11:32
  • It will not differ in any way, that's why I said that both things do almost the same thing, the only difference is that he is writing boilerplate code with the TaskCompletionSource. – Tomas Tomov Apr 13 '21 at 11:36