title: How do I wait for all other threads to finish their tasks?
body: <p>I have several threads consuming tasks from a queue using something similar to the code below. The problem is that there is one type of task which cannot run while any other tasks are being processed.</p>
  
  <p>Here is what I have:</p>
  
  <pre><code>while (true) // Threaded code
  {
      while (true)
      {
          lock(locker)
          {
              if (close_thread)
                  return;
  
              task = GetNextTask(); // Get the next task from the queue
          }
  
          if (task != null)
              break;
  
          wh.WaitOne(); // Wait until a task is added to the queue
      }
  
      task.Run();
  }
  </code></pre>
  
  <p>And this is kind of what I need:</p>
  
  <pre><code>while (true)
  {
      while (true)
      {
          lock(locker)
          {
              if (close_thread)
                  return;
  
              if (disable_new_tasks)
              { 
                  task = null; 
              }
              else
              {
                  task = GetNextTask();
              }
          }
  
          if (task != null)
              break;
  
          wh.WaitOne();
      }
  
      if(!task.IsThreadSafe())
      {
          // I would set this to false inside task.Run() at 
          // the end of the non-thread safe task
          disable_new_tasks = true;  
          Wait_for_all_threads_to_finish_their_current_tasks(); 
      }
  
      task.Run();
  }
  </code></pre>
  
  <p>The problem is I don't know how to achive this without creating a mess.</p>