title: How to terminate a dispatched thread in WPF
body: <p>I have a simple and very literal WPF wherein when I click start, it will start doing work and if I click stop, it will stop. Code for starting the worker/background thread is:</p>
  
  <pre><code>--- variables ---
  Thread[] thd;
  bflag = false;
  
  --- Start background worker when Start button is clicked ---
  private void btnStart_Click(object sender, RoutedEventArgs e)
  {
     Thread startFileCopy = new Thread(() =&gt; startFC());
     startFileCopy.Start();  
  }
  
  --- StartFC code ---
  private void startFC()
  {
     bflag = true;
     thd = new Thread[3];
     for(int i=0; i&lt;3; i++)
     {
        thd[i] = new Thread(copynow);
        thd[i].Start();
     }
  }
  
  --- copynow code ---
  private void copynow()
  {
     while(bflag)
     {
        if (filecount == 0)
          bflag = false;
        else
        {
           // --- copy file ---
           Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
                 new Action(() =&gt; copyFile(&lt;filename to be copied&gt;)));
           // --- update progressbar ---
           Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
                 new Action(() =&gt; updateProgressbar(++1)));
        }
     }
  }
  </code></pre>
  
  <p>Now to stop this, on my cancel button, I dispatched another thread with Send as priority to set bflag to false. However, based on the responses on my UI, the progressbar is still updating and the file copy still continues. Code for my stop button:</p>
  
  <pre><code>--- Stop when stop button is clicked ---
  private void btnStop_Click(object sender, RoutedEventArgs e)
  {
     Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Send, 
                new Action(() =&gt; stopThreads()));
  }
  
  --- stopThreads code ---
  private void stopThreads()
  {
     bflag = false;
     if (thd != null)
       for (int i = 0; i &lt; THREAD_COUNT; i++)
         if (thd[i].IsAlive)
            thd[i].Join(3000);
  }
  </code></pre>
  
  <p>What am I doing wrong? Thanks in advance!</p>