How to correctly stop thread which is using Control.Invoke
        Posted  
        
            by codymanix
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by codymanix
        
        
        
        Published on 2010-05-28T08:39:18Z
        Indexed on 
            2010/05/28
            8:41 UTC
        
        
        Read the original article
        Hit count: 359
        
I tried the following (pseudocode) but I always get a deadlock when Iam trying to stop my thread. The problem is that Join() waits for the thread to complete and a pending Invoke() operation is also waiting to complete. How can I solve this?
Thread workerThread = new Thread(BackupThreadRunner);
volatile bool cancel;
// this is the thread worker routine
void BackupThreadRunner()       
{
  while (!cancel)
  { 
     DoStuff();
     ReportProgress();
  }
}
// main thread
void ReportProgress()
{
   if (InvokeRequired)
   {
      Invoke(ReportProgress);
   }
   UpdateStatusBarAndStuff();
}
// main thread
void DoCancel()
{
   cancel=true;
   workerThread.Join();
}
© Stack Overflow or respective owner