none
Background Worker and Thread.Sleep RRS feed

  • Question

  • I have a background worker process that I place in sleep for 30 seconds. This background working is instantiated from a windows form. How do I click a button on the windows form and interrupt the sleeping background worker and "wake up" that thread?

    Here is my DoWork event handler.

    private void backgroundWorker1_DoWork( object sender, DoWorkEventArgs e )
    {
       BackgroundWorker bw = sender as BackgroundWorker;
       while ( !bw.CancellationPending )
       {
          Thread.Sleep( 30000 );
       }
       if ( bw.CancellationPending )
       {
          e.Cancel = true;
       }			
    }


    • Edited by dgrm44 Friday, April 27, 2012 7:53 PM format code
    Friday, April 27, 2012 5:57 PM

Answers

  • Have the background worker call the WaitOne method with a timeout. The timeout should be thirty seconds. This will give you exactly the behavior you're looking for: the thread sleeps for thirty seconds, unless another thread wakes it up (by calling Set()).

    • Proposed as answer by Kris444 Saturday, April 28, 2012 3:31 AM
    • Marked as answer by dgrm44 Monday, April 30, 2012 12:34 PM
    Friday, April 27, 2012 11:03 PM

All replies

  • You create an AutoResetEvent and instead of having the background worker sleep, you have it wait on the AutoResetEvent for 30 seconds. Then any other thread can Set the AutoResetEvent to cause the waiting background worker to continue on.
    • Proposed as answer by Kris444 Saturday, April 28, 2012 3:31 AM
    Friday, April 27, 2012 6:14 PM
  • Can you paste a code example?
    Friday, April 27, 2012 6:17 PM
  • I don't believe I can add anything of value that's not already on the msdn documentation page for AutoResetEvent.
    Friday, April 27, 2012 9:20 PM
  • I have reviewed the documentation you refer to and I am not connecting the dots. If you are not willing to post a sample explaining how to use AutoResetEvent to make a background worker sleep for 30 seconds then awaken and do some work and sleep again then maybe someone else is?

    The only thing I can think of is to use a timer outside of the background worker and every thirty seconds call AutoResetEvent SET to the background worker and then have it call AutoResetEvent WAITONE within the DoWork handler?

    Friday, April 27, 2012 10:51 PM
  • Have the background worker call the WaitOne method with a timeout. The timeout should be thirty seconds. This will give you exactly the behavior you're looking for: the thread sleeps for thirty seconds, unless another thread wakes it up (by calling Set()).

    • Proposed as answer by Kris444 Saturday, April 28, 2012 3:31 AM
    • Marked as answer by dgrm44 Monday, April 30, 2012 12:34 PM
    Friday, April 27, 2012 11:03 PM
  • I missed that overloaded method, thanks!

    Friday, April 27, 2012 11:33 PM