c# - 我如何等待所有其他线程完成它们的任务?

标签 c# multithreading xbox360

我有几个线程使用类似于下面代码的东西从队列中消耗任务。问题是有一种类型的任务无法在处理任何其他任务时运行。

这是我的:

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 方法来确定所有线程都已完成执行。

MSDN

关于c# - 我如何等待所有其他线程完成它们的任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4524961/

相关文章:

xbox360 - 获取用户 Xbox 成就列表?

c# - 是否可以从 XNA 发送电子邮件?

c++ - 断言失败 - 在 Unity-Xbox 上崩溃

c# - 如何在嵌套 linq 查询字段中搜索一组单词

C# 泛型类型推断与协变 - 错误或限制

delphi - 多线程(TThread)Delphi应用程序不会终止

java - 灵活的倒计时?

c# - 如何在 LINQ 连接中使用 AND

c# - 在不可变对象(immutable对象)上创建一个 "with"方法

c# - 如何防止使用多线程插入重复值