Reputation: 403
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.
Upvotes: 1
Views: 3857
Reputation: 4949
You should use a semaphore to sync between the threads.
once you want the background worker to "sleep", grap a handle on the semaphore, once you click on the "wake up" button, release the semaphore and the background worker will resume..
From your GUI thread (the one that shows the button) your should declare
Semaphore s = new Semaphore(0, 1);
on the background worker thread - this statement initialize a semaphore with a default value of 0 (locked)
on your backgroundworker thread/code call:
s.WaitOne();
this statement actually cause the background worker to wait until the semaphore is released by the gui thread (your wake up button).
on the button click handler, call the:
s.Release();
the release operation allows the background worker code to resume running.
Upvotes: 0
Reputation: 53729
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 true
I would block the thread by waiting on ManualResetEvent
. When you want to resume the processing you set the boolean to false and use the Set()
method of the ManualResetEvent to release allow the code to continue.
Upvotes: 3
Reputation: 8494
You have to look at ManualResetEvent
Usage:
ManualResetEvent e = new ManualResetEvent(false); //global variable
e.WaitOne(); // Thread will wait until event is triggered
e.Set(); // Trigger event from other thread
Upvotes: 2