Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : How to pause the thread and continue when some event occur?

Tags:

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?

like image 325
Prince OfThief Avatar asked Jan 31 '11 06:01

Prince OfThief


2 Answers

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
}
like image 187
Marlon Avatar answered Sep 22 '22 22:09

Marlon


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).

like image 45
Marc Gravell Avatar answered Sep 22 '22 22:09

Marc Gravell