【问题标题】:How correctly wait of ends of thread array on c#? [closed]在 C# 上如何正确等待线程数组的结束? [关闭]
【发布时间】:2020-04-01 15:58:01
【问题描述】:

我需要使用明确的线程类(不是任务,也没有异步/等待)。如何正确等待列表中所有任务的结束?

我想要正确的方法 WaitAll()

例如:

public class TaskManager
{
    private readonly List<Thread> _threads = new List<Thread>();

    public void AddTask([NotNull] Action<int> action, int i)
    {
        var thread = new Thread(() =>
        {
            action(i);
        });
        _threads.Add(thread);
        thread.Start();
    }

    public void WaitAll()
    {
        while (_threads.Any(x => x.ThreadState != ThreadState.Stopped))
        {
        }
    }
}

【问题讨论】:

  • 为什么需要 "clear thread class (not Task ...)" ?这立即使它看起来像一个 X/Y 问题。
  • public void WaitAll() { foreach (var t in _threads) t.Join(); }
  • 我在 FW 3.5 的项目中需要它
  • 在 3.5 中您至少拥有 ThreadPool,但这会使您的管理变得非常不同。甚至可能没有必要。

标签: c# .net-3.5


【解决方案1】:

我质疑“裸线程”的必要性,但是当您确定这一点时,在 while 循环中等待就是在浪费 CPU 时间。线程只有 Join() 方法可用:

public void WaitAll()
{
   foreach(var thread in _threads)    
     thread.Join();
}

【讨论】:

    猜你喜欢
    • 2012-07-13
    • 2021-11-03
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    相关资源
    最近更新 更多