Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task continuation with own ThreadPool

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.

like image 515
Martin Walter Avatar asked May 30 '14 16:05

Martin Walter


People also ask

Does Task use ThreadPool?

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.

Does a Task run on a separate thread C#?

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.

Does Task create new thread?

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.

Which threading Task method will create a Task that will complete when any of the associated tasks have completed?

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.


1 Answers

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.

like image 151
i3arnon Avatar answered Nov 15 '22 14:11

i3arnon