title: Share data between threads
body: <p>I'm trying to implement an algorithm that should run in parallel using threads or tasks. The difficulty is that I want the threads/tasks to share their best results from time to time with all other threads.</p>
  
  <p>The basic idea is this:</p>
  
  <pre><code>//Accessible from each thread
  IProducerConsumerCollection&lt;MyObject&gt; _bestObjects;
  
  //Executed in each thread
  DoSomeWork(int n){
      MyObject localObject;
      for(var i = 0; i &lt; n; i++){
          //Do some calculations and store results in localObject
          if((i/n)%0.5 == 0)
          {
              //store localObject in _bestObjects
              //wait until each thread has stored its result in _bestObjects
              //get the best result from _bestObjects and go on
          } 
      }
  }
  </code></pre>
  
  <p>How can this be achieved using System.Threading or System.Threading.Tasks and is it true that tasks should not be used for long running operations? </p>
  
  <h2>Update: Clarification</h2>
  
  <p>It's not my problem to have a thread safe collection but to make the threads stop, publish result, wait until all other threads have publihed their results to and then go on again. All threads will run simultaneously.
  Cutting a long story short:</p>
  
  <ol>
  <li>Whats better for long running operations? Task or Thread or anything else?</li>
  <li>How to communicate between threads/taks to inform each of them about the state of all other assuming that the number of threads is set at runtime (depending on available cores).</li>
  </ol>
  
  <p>Best Regards</p>
  
  <p>Jay</p>