How can I pause a thread and continue when some event occur?
I want the thread to continue when a button is clicked.
Someone told me that thread.suspend
is not the proper way to pause a thread.
Is there another solution?
You could use a System.Threading.EventWaitHandle.
An EventWaitHandle blocks until it is signaled. In your case it will be signaled by the button click event.
private void MyThread()
{
// do some stuff
myWaitHandle.WaitOne(); // this will block until your button is clicked
// continue thread
}
You can signal your wait handle like this:
private void Button_Click(object sender, EventArgs e)
{
myWaitHandle.Set(); // this signals the wait handle and your other thread will continue
}
Indeed, suspending a thread is bad practice since you very rarely know exactly what a thread is doing at the time. It is more predictable to have the thread run past a ManualResetEvent
, calling WaitOne()
each time. This will act as a gate - the controlling thread can call Reset()
to shut the gate (pausing the thread, but safely), and Set()
to open the gate (resuming the thread).
For example, you could call WaitOne
at the start of each loop iteration (or once every n
iterations if the loop is too tight).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With