In my program, there will be a time where I have to call
Thread.Sleep(Timeout.Infinite);
to “temporarily pause” the BackgroundWorker. A groupbox will be shown before the backgroundworker thread sleeps. That groupbox has a button that should “wake up” the backgroundworker thread and continue it.
If I call Thread.Interrupt() (which by the way I can’t seem to use unless I create a Thread object, which I shouldn’t do) at the button_Click event, like:
private void button1_Click(object sender, EventArgs e)
{
Thread.Interrupt(); //interrupt thread
}
The Thread it “would” interrupt is the UI Thread, am I right? What I need to do is to Interrupt the BackgroundWorker thread. How do I do this?
EDIT: Thanks for those that replied to this question. I’ll use AutoResetEvent. Seems more appropriate for my use.
Let me start with the high-level concept:
What you should do is have a token that you check every so often in the code that is being executed by the BackgroundWorker. When the token is set your background code will stop the normal flow and just check the token every now and then and when the token is cleared the background code can continue processing.
So the interesting part above is the token. What I would do is maybe have a boolean that I check and when that boolean is set to
trueI would block the thread by waiting onManualResetEvent. When you want to resume the processing you set the boolean to false and use theSet()method of the ManualResetEvent to release allow the code to continue.