Task continuation with own ThreadPool

.net, async-await, c#, task-parallel-library

Solution

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.

Problem

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.

Original source

Related problems