【问题标题】:C#: Waiting for all threads to completeC#:等待所有线程完成
【发布时间】:2010-09-20 18:11:39
【问题描述】:

我在编写的代码中遇到了一个常见模式,我需要等待组中的所有线程完成并超时。超时应该是 所有 线程完成所需的时间,因此简单地为每个线程执行 thread.Join(timeout) 是行不通的,因为可能的超时是 timeout * numThreads。

现在我做了如下的事情:

var threadFinishEvents = new List<EventWaitHandle>();

foreach (DataObject data in dataList)
{
    // Create local variables for the thread delegate
    var threadFinish = new EventWaitHandle(false, EventResetMode.ManualReset);
    threadFinishEvents.Add(threadFinish);

    var localData = (DataObject) data.Clone();
    var thread = new Thread(
        delegate()
        {
            DoThreadStuff(localData);
            threadFinish.Set();
        }
    );
    thread.Start();
}

Mutex.WaitAll(threadFinishEvents.ToArray(), timeout);

不过,这种事情似乎应该有一个更简单的成语。

【问题讨论】:

  • 我会这样做——想不出更简单的方法。
  • 有完整源代码工作的最终解决方案吗?可能更复杂的示例用于通知每个线程中的错误,并且在 WaitAll 显示摘要之后?

标签: c# multithreading


【解决方案1】:

在我的脑海中,你为什么不只是 Thread.Join(timeout) 并从总超时中删除加入所花费的时间?

// pseudo-c#:

TimeSpan timeout = timeoutPerThread * threads.Count();

foreach (Thread thread in threads)
{
    DateTime start = DateTime.Now;

    if (!thread.Join(timeout))
        throw new TimeoutException();

    timeout -= (DateTime.Now - start);
}

编辑: 代码现在不那么伪了。不明白当你修改 +4 的答案完全相同时,为什么你要修改答案 -2,只是不太详细。

【讨论】:

  • 这是不正确的:给定所有线程的完全超时,任何任何线程(包括正在等待的第一个线程)都可能消耗完全超时。您的代码不会检查加入的结果。
  • 首先,这是伪代码,因为它不是真正的代码,所以不完整。我假设一个等于或小于零的时间会抛出什么的。其次,如果第一个线程消耗了整个时间,那么操作应该整体超时。根据问题,这是正确的。
【解决方案2】:

我仍然认为使用 Join 更简单。记录预期完成时间(如Now+timeout),然后循环执行

if(!thread.Join(End-now))
    throw new NotFinishedInTime();

【讨论】:

    【解决方案3】:

    这可能不适合您,但如果您可以使用 .NET 并行扩展,那么您可以使用 Tasks 代替原始线程,然后使用 Task.WaitAll() 等待它们完成。

    【讨论】:

      【解决方案4】:

      我想弄清楚如何做到这一点,但我无法从谷歌得到任何答案。 我知道这是一个旧线程,但这是我的解决方案:

      使用以下类:

      class ThreadWaiter
          {
              private int _numThreads = 0;
              private int _spinTime;
      
              public ThreadWaiter(int SpinTime)
              {
                  this._spinTime = SpinTime;
              }
      
              public void AddThreads(int numThreads)
              {
                  _numThreads += numThreads;
              }
      
              public void RemoveThread()
              {
                  if (_numThreads > 0)
                  {
                      _numThreads--;
                  }
              }
      
              public void Wait()
              {
                  while (_numThreads != 0)
                  {
                      System.Threading.Thread.Sleep(_spinTime);
                  }
              }
          }
      
      1. 在执行线程之前调用 Addthreads(int numThreads)。
      2. 在每个完成后调用 RemoveThread()。
      3. 在您希望等待所有线程完成时使用 Wait() 在继续之前

      【讨论】:

        【解决方案5】:

        既然问题被碰到了,我会继续发布我的解决方案。

        using (var finished = new CountdownEvent(1)) 
        { 
          for (DataObject data in dataList) 
          {   
            finished.AddCount();
            var localData = (DataObject)data.Clone(); 
            var thread = new Thread( 
                delegate() 
                {
                  try
                  {
                    DoThreadStuff(localData); 
                    threadFinish.Set();
                  }
                  finally
                  {
                    finished.Signal();
                  }
                } 
            ); 
            thread.Start(); 
          }  
          finished.Signal(); 
          finished.Wait(YOUR_TIMEOUT); 
        } 
        

        【讨论】:

          【解决方案6】:

          使用 .NET 4.0,我发现 System.Threading.Tasks 更易于使用。这是对我来说可靠的旋转等待循环。它阻塞主线程,直到所有任务完成。还有Task.WaitAll,但这并不总是对我有用。

                  for (int i = 0; i < N; i++)
                  {
                      tasks[i] = Task.Factory.StartNew(() =>
                      {               
                           DoThreadStuff(localData);
                      });
                  }
                  while (tasks.Any(t => !t.IsCompleted)) { } //spin wait
          

          【讨论】:

          • 你想要Task.WaitAll(tasks) 而不是那个旋转。
          • @T.Webster - 你说Task.WaitAll 并不总是适合你是什么意思?你是在暗示这种方法有错误吗?你能提供例子吗。它总是对我有用。另一方面,你建议的旋转是相当昂贵的事情。你正在锤击你的 CPU。 Task.WaitAll 是更好的解决方案。
          • 如果您使用此选项,我建议至少将Thread.Yield() 放在while 正文中。
          • 抱歉,-1 表示 spinwait。没有更多细节的动机“Task.WaitAll 并不总是对我有用”不是这样做的正当借口。
          • 我体验过 WaitAll 在 4.0 中并不总是正常工作。也许这是任务本身的问题。我通常希望在任务上记录一个结果,并且经常体验到一个任务永远不会写出结果(任务中的最后一件事)。要么全部要么少一个。没有两个、三个或 N 个缺失。当它发生时,总是只有一个。我确实尝试了不同的旋转选项来检查结果数量是否与任务数量匹配,并且它从未退出该循环。即使 WaitAll 被释放,任务在完成之前就消失了。
          【解决方案7】:

          可能的解决方案:

          var tasks = dataList
              .Select(data => Task.Factory.StartNew(arg => DoThreadStuff(data), TaskContinuationOptions.LongRunning | TaskContinuationOptions.PreferFairness))
              .ToArray();
          
          var timeout = TimeSpan.FromMinutes(1);
          Task.WaitAll(tasks, timeout);
          

          假设dataList是item的列表,每个item需要在单独的线程中处理。

          【讨论】:

          • 每个线程中的通知错误以及 WaitAll 显示摘要之后的更复杂示例?
          【解决方案8】:

          我阅读了《C# 4.0:Herbert Schildt 的完整参考》一书。作者使用join给出了解决方案:

          class MyThread
              {
                  public int Count;
                  public Thread Thrd;
                  public MyThread(string name)
                  {
                      Count = 0;
                      Thrd = new Thread(this.Run);
                      Thrd.Name = name;
                      Thrd.Start();
                  }
                  // Entry point of thread.
                  void Run()
                  {
                      Console.WriteLine(Thrd.Name + " starting.");
                      do
                      {
                          Thread.Sleep(500);
                          Console.WriteLine("In " + Thrd.Name +
                          ", Count is " + Count);
                          Count++;
                      } while (Count < 10);
                      Console.WriteLine(Thrd.Name + " terminating.");
                  }
              }
              // Use Join() to wait for threads to end.
              class JoinThreads
              {
                  static void Main()
                  {
                      Console.WriteLine("Main thread starting.");
                      // Construct three threads.
                      MyThread mt1 = new MyThread("Child #1");
                      MyThread mt2 = new MyThread("Child #2");
                      MyThread mt3 = new MyThread("Child #3");
                      mt1.Thrd.Join();
                      Console.WriteLine("Child #1 joined.");
                      mt2.Thrd.Join();
                      Console.WriteLine("Child #2 joined.");
                      mt3.Thrd.Join();
                      Console.WriteLine("Child #3 joined.");
                      Console.WriteLine("Main thread ending.");
                      Console.ReadKey();
                  }
              }
          

          【讨论】:

            【解决方案9】:

            这没有回答问题(没有超时),但我做了一个非常简单的扩展方法来等待集合的所有线程:

            using System.Collections.Generic;
            using System.Threading;
            namespace Extensions
            {
                public static class ThreadExtension
                {
                    public static void WaitAll(this IEnumerable<Thread> threads)
                    {
                        if(threads!=null)
                        {
                            foreach(Thread thread in threads)
                            { thread.Join(); }
                        }
                    }
                }
            }
            

            然后你只需调用:

            List<Thread> threads=new List<Thread>();
            //Add your threads to this collection
            threads.WaitAll();
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-03-30
              相关资源
              最近更新 更多