Spawn Multiple Threads for work then wait until all finished

后端 未结 12 1570
遇见更好的自我
遇见更好的自我 2020-11-28 01:46

just want some advice on \"best practice\" regarding multi-threading tasks.

as an example, we have a C# application that upon startup reads data from various \"type

12条回答
  •  猫巷女王i
    2020-11-28 01:56

    Here are two patterns for waiting on multiple parallel operations. The trick is that you have to treat your main thread as if it were one of the parallel operations as well. Otherwise, there is a subtle race condition between the signalling of completion in the worker threads and the waiting on that signal from the main thread.

    int threadCount = 1;
    ManualResetEvent finished = new ManualResetEvent(false);
    for (int i = 0; i < NUM_WORK_ITEMS; i++)
    {
      Interlocked.Increment(ref threadCount); 
      ThreadPool.QueueUserWorkItem(delegate 
      { 
          try 
          { 
               // do work 
          } 
          finally 
          { 
              if (Interlocked.Decrement(ref threadCount) == 0) finished.Set();
          } 
      }); 
    }
    if (Interlocked.Decrement(ref threadCount) == 0) finished.Set();
    finished.WaitOne(); 
    

    As a personal preference I like using the CountdownEvent class to do the counting for me which is available in .NET 4.0.

    var finished = new CountdownEvent(1);
    for (int i = 0; i < NUM_WORK_ITEMS; i++)
    {
      finished.AddCount();
      ThreadPool.QueueUserWorkItem(delegate 
      { 
          try 
          { 
               // do work 
          } 
          finally 
          { 
            finished.Signal();
          } 
      }); 
    }
    finished.Signal();
    finished.Wait(); 
    

    The examples above use the ThreadPool, but you can swap that for whatever threading mechanism you prefer.

提交回复
热议问题