title: How to manage a list of tasks using the Task Parallel Library
body: <p>I'm trying to manage a list of tasks for a Windows Service so when I shut down the Service, I can use the Task.WaitAll() method to stop the Service from shutting down until all of the remaining tasks complete. For example, I have a Run() method that executes until a boolean is updated:</p>
  
  <pre><code>public void Run()
  {
      while (runFlag)
      {
          if (MaxTasksAchieved)
          {
              System.Threading.Thread.Sleep(pollingInterval);
          }
          else
          {
  
              taskList.Add(Task.Factory.StartNew(() =&gt;
              {
                  // do stuff
              }));
          }
      }
  }
  </code></pre>
  
  <p>Then in my Stop() method, I have the following:</p>
  
  <pre><code>public void Stop()
  {
      runFlag = false;
  
      if (taskList.Count &gt; 0)
      {
          // wait
          Task.WaitAll(taskList.ToArray());
      }
      else
      {
          // no wait, great.
      }
  }
  </code></pre>
  
  <p>My question is how do I elegantly have the task remove itself from the list after it's done executing? I want the task to remove itself from the list so when Stop() is called, taskList only contains the tasks that are currently in progress.</p>