Search code examples
c#multithreadingwait

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


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?


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
    }