title: How to remove Task from collection after completed
body: <p>Let's say I have a collection of <code>System.Threading.Tasks.Task</code>:</p>
  
  <pre><code>HashSet&lt;Task&gt; myTasks = new HashSet&lt;Task&gt;();
  </code></pre>
  
  <p>...and I periodically feed more into the collection as I have more data that needs to be processed:</p>
  
  <pre><code>foreach (DataItem item in itemsToProcess)
      myTasks.Add(
          Task.Factory.StartNew(
              () =&gt; Process(item),
              cancellationToken,
              TaskCreationOptions.LongRunning,
              TaskScheduler.Default));    
  </code></pre>
  
  <p>Since <code>Task</code>s remain in <code>TaskStatus.RanToCompletion</code> status after finishing instead of just disappearing, they would remain in the collection until explicitly removed and the collection would grow indefinitely.  The <code>Task</code>s need to be pruned to prevent this.</p>
  
  <p>One approach I have looked at is giving the <code>Task</code> access to the collection and having it remove itself at the very end.  But I am also looking at an architecture where I would have to remove a Task that my component has not created.  My first thought is to attach a trigger or event to completion of each Task, something like this:</p>
  
  <pre><code>foreach (Task task in createdSomewhereElse)
  {
      lock (myTasks) myTasks.Add(task);
      task.WhenTaskIsCompleted += 
          (o, ea) =&gt; { lock(myTasks) myTasks.Remove(task); };
      task.Start();
  }
  </code></pre>
  
  <p>...but <code>Task</code> has no such event.  Is there any good way to accomplish what I'm looking for?  Something like this:</p>