【发布时间】: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,但这会使您的管理变得非常不同。甚至可能没有必要。