Create multiple threads and wait all of them to complete

前端 未结 8 1964
星月不相逢
星月不相逢 2020-12-02 15:13

How can I create multiple threads and wait for all of them to complete?

8条回答
  •  隐瞒了意图╮
    2020-12-02 15:36

    In my case, I could not instantiate my objects on the the thread pool with Task.Run() or Task.Factory.StartNew(). They would not synchronize my long running delegates correctly.

    I needed the delegates to run asynchronously, pausing my main thread for their collective completion. The Thread.Join() would not work since I wanted to wait for collective completion in the middle of the parent thread, not at the end.

    With the Task.Run() or Task.Factory.StartNew(), either all the child threads blocked each other or the parent thread would not be blocked, ... I couldn't figure out how to go with async delegates because of the re-serialization of the await syntax.

    Here is my solution using Threads instead of Tasks:

    using (EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.ManualReset))
    {
      int outdex = mediaServerMinConnections - 1;
      for (int i = 0; i < mediaServerMinConnections; i++)
      {
        new Thread(() =>
        {
          sshPool.Enqueue(new SshHandler());
          if (Interlocked.Decrement(ref outdex) < 1)
            wh.Set();
        }).Start();
      }
      wh.WaitOne();
    }
    

提交回复
热议问题