none
Threads synchronization RRS feed

  • Question

  • Hi!

    Please consult me on the following question:

    1. There is main GUI thread, two buttons Start and ReStart

    2. ManualResetEvent is used to stop the working thread 

    3. "Start" creates and starts the thread

       {
          workThread = new Thread(() => DoWork());
          workThread.Start();
       }

      void DoWork()
      {         
         while (true)
         {              
            Thread.Sleep(1000);

             MethodInvoker methodInvoker = delegate() { "Update GUI" };
             this.Invoke(methodInvoker);

             if (manualResetEvent.WaitOne(0))
             {                    
                break;
             }                                                                
          }            
       }

    4. ReStart should stop the thread and start new one with the same DoWork method.

    My question is how correctly stop current thread and start new one?

    {
      manualResetEvent.Set();

      //Incorrect because first thread can be still alive

      workThread = new Thread(() => DoWork());
      workThread.Start();
    }

    {
      manualResetEvent.Set();

      //Incorrect because there will be a deadlock on GUI thread
      workThread.Join();    

      workThread = new Thread(() => DoWork());
      workThread.Start();
    }

    Please advice correct implementation (maybe using tasks or other stuff from TPL)

    Thank you

    Alexander

    Thursday, July 3, 2014 1:37 PM

Answers

  • Instead of doing a Thread.Sleep you should do your WaitOne for the ManualResetEvent, have it wait for the desired duration, and if not signaled, then do work.

    You can have reset use WaitHandle.SignalAndWait to get a hand off from the DoWork thread that it's finished.

    Thursday, July 3, 2014 7:29 PM