我有几个线程使用类似于下面代码的东西从队列中消耗任务。问题是有一种类型的任务无法在处理任何其他任务时运行。
这是我的:
while (true) // Threaded code
{
while (true)
{
lock(locker)
{
if (close_thread)
return;
task = GetNextTask(); // Get the next task from the queue
}
if (task != null)
break;
wh.WaitOne(); // Wait until a task is added to the queue
}
task.Run();
}
这就是我需要的:
while (true)
{
while (true)
{
lock(locker)
{
if (close_thread)
return;
if (disable_new_tasks)
{
task = null;
}
else
{
task = GetNextTask();
}
}
if (task != null)
break;
wh.WaitOne();
}
if(!task.IsThreadSafe())
{
// I would set this to false inside task.Run() at
// the end of the non-thread safe task
disable_new_tasks = true;
Wait_for_all_threads_to_finish_their_current_tasks();
}
task.Run();
}
问题是我不知道如何在不造成困惑的情况下实现这一目标。
最佳答案
尝试使用 TreadPool,然后使用 WaitHandle.WaitAll 方法来确定所有线程都已完成执行。
关于c# - 我如何等待所有其他线程完成它们的任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4524961/