title: Best Practice LongRunning Task creation
body: <p>Is this a good design for a background thread that needs to be run using the Task API in .Net 4?  My only concern is if we want to cancel that task how I would do it? I know I can just set <code>ProgramEnding</code> to <code>true</code> but I know there is a <code>CancellationToken</code> in the Task API.</p>
  
  <p>This is just an example sample of code so that one thread will be adding to a collection and another thread will be removing from it.  The Task is setup as LongRunning as this needs to be running continuously whilst the program is running</p>
  
  <pre><code>private void RemoveFromBlockingCollection()
  {
      while (!ProgramEnding)
      {
         foreach (var x in DataInQueue.GetConsumingEnumerable())
         {
            Console.WriteLine("Task={0}, obj={1}, Thread={2}"
                            , Task.CurrentId, x + " Removed"
                            , Thread.CurrentThread.ManagedThreadId);
         }
      }
  }
  
  private void button1_Click(object sender, EventArgs e)
  {
     DataInQueue = new BlockingCollection&lt;string&gt;();
     var t9 = Task.Factory.StartNew(RemoveFromBlockingCollection
                                   , TaskCreationOptions.LongRunning);
  
     for (int i = 0; i &lt; 100; i++)
     {
       DataInQueue.Add(i.ToString());
       Console.WriteLine("Task={0}, obj={1}, Thread={2}", 
                         Task.CurrentId, i + " Added", 
                         Thread.CurrentThread.ManagedThreadId);
       Thread.Sleep(100);
     }
     ProgramEnding = true;
  }
  </code></pre>
  
  <p><strong>UPDATE:</strong> I have found that I can remove the ProgramEnding boolean and use DataInQueue.CompleteAdding which which bring the thread to an end.</p>