Is it possible to force the continuation of an async-await statement to run on a thread of a custom ThreadPool?
Context: I'm running an ASP-Application and doing quite a bit of work in the background. I'm doing all the work via a self written ThreadPool, but if I use the async-await Pattern, the continuation always runs on a thread named "Worker Thread". I'm pretty sure that's a thread from the default ThreadPool which is also used to process HTTP requests. This leads to a starvation of these requests as all the threads of the default ThreadPool are busy continuing my background work.
Using the thread pool The easiest way to use the thread pool is to use the Task Parallel Library (TPL). By default, TPL types like Task and Task<TResult> use thread pool threads to run tasks. You can also use the thread pool by calling ThreadPool.
Run() or similar constructs, a task runs on a separate thread (mostly a managed thread-pool one), managed by the . NET CLR. But that depends on the actual implementation of the task.
Task is more abstract then threads. It is always advised to use tasks instead of thread as it is created on the thread pool which has already system created threads to improve the performance. The task can return a result. There is no direct mechanism to return the result from a thread.
Wait method. A call to the Wait method blocks the calling thread until the single class instance has completed execution. The following example calls the parameterless Wait() method to wait unconditionally until a task completes. The task simulates work by calling the Thread.
Yes. You can create a custom SynchronizationContext
that works with your custom ThreadPool
and set it before running the async operation.
var prevCtx = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(new ThreadPoolSynchronizationContext());
// async operations.
}
finally
{
SynchronizationContext.SetSynchronizationContext(prevCtx);
}
More on how to create a custom SynchronizationContext
: Await, SynchronizationContext, and Console Apps
Although a custom ThreadPool is rarely necessary. You should probably try and optimize while using the built-in one instead.
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