title: exception handling on background threads using Thread pool
body: <p>The application I am working on uses thread pool. Here's the basic pseudo code.</p>
  
  <p>On the main thread</p>
  
  <pre><code>foreach(Object obj in Component.GetObject())    
  {    
      //Invoke the thread pool providing the call back (method to be called on the background// thread) and pass the object as the parameter.
  }
  //Wait for the threads to complete.
  </code></pre>
  
  <p>The "Component.GetObject" will basically return a CLR object using Yield return. This object needs to be processed by two other components on threads. So we are invoking the thread pool providing the call back method (that will invoke the two components).</p>
  
  <p>If there is an exception on the spawned thread/s, the parent thread needs to be notified so that it can break out of the for loop (i.e. stop spawing more threads), wait for the spawned threads to complete and then handle the exception.</p>
  
  <p>Based on my reading, one of the approaches would be have a "flag" variable on the main thread. If there is an exception on the spawned thread, the thread would set the variable using locking mechanism. The parent thread would check the "flag" variable before spawning new threads.</p>
  
  <p>I would like to know if there is a better approach for handling this scenario. Thread pool is being used since it manages the queueing of threads if the "for" loop spawns more threads than the thread pool limit.</p>