Junior — Middle
How is the mechanism for waiting for task completion within a thread pool implemented?
sobes.tech AI
Answer from AI
In C#, the mechanism for waiting for tasks to complete within a thread pool is usually implemented using the Task class and synchronization methods such as Task.Wait(), Task.WaitAll(), or Task.WhenAll().
When tasks are started in a thread pool via Task.Run or ThreadPool.QueueUserWorkItem, you can wait for their completion by calling:
Task[] tasks = new Task[3];
tasks[0] = Task.Run(() => { /* work */ });
tasks[1] = Task.Run(() => { /* work */ });
tasks[2] = Task.Run(() => { /* work */ });
// Wait for all tasks to complete
Task.WaitAll(tasks);
If ThreadPool is used directly, you can apply ManualResetEvent or CountdownEvent for waiting:
CountdownEvent countdown = new CountdownEvent(3);
for (int i = 0; i < 3; i++)
{
ThreadPool.QueueUserWorkItem(_ => {
// work
countdown.Signal(); // decrement the counter
});
}
// Wait for all tasks to complete
countdown.Wait();
Thus, the waiting mechanism is based on thread synchronization and the use of special methods and classes to block the current thread until all launched tasks are completed.