Junior — Middle
Kuidas rakendatakse ootamismehhanismi ülesannete lõpetamise ootamiseks niidupakis?
sobes.tech AI
Vastus AI-lt
In C#, the wait mechanism for task completion 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 using ThreadPool 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 counter
});
}
// Wait for all tasks to complete
countdown.Wait();
Thus, the wait 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.