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

Prince OfThief picture Prince OfThief · Jan 31, 2011 · Viewed 18.8k times · Source

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?

Answer

Marlon picture Marlon · Jan 31, 2011

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
}