title: Cancel task and wait for it to finish
body: <p>I have a time consuming task which I need to run in a separate thread to avoid locking the GUI thread. As this task progresses, it updates a specific GUI control.</p>
  
  <p>The catch is that the user might move to another part of the GUI before the task is over, and in that case, I have to:</p>
  
  <ol>
  <li>Cancel the ongoing task (if it is active)</li>
  <li>Wait till it's done cancelling: this is crucial, because the time consuming task's objective is to update a specific control. If more than one thread tries to do it at once, things might get messy.</li>
  <li>Launch the task from scratch</li>
  </ol>
  
  <p>For a concrete example, imagine the form has two parts: one where you navigate a directory tree, and another where you display thumbnails. When the user navigates to another directory, thumbnails need to be refreshed.</p>
  
  <p>First I thought of using a <code>BackgroundWorker</code> and an <code>AutoResetEvent</code> to wait for cancellation, but I must have messed something because I got deadlocked when cancelling. Then I read about TPL, which is supposed to replace BGW and more primitive mechanisms.</p>
  
  <p>Can this be done easily using TPL?</p>