how to pause/resume a thread

Yustme picture Yustme · May 6, 2012 · Viewed 40.1k times · Source

How can I pause/resume a thread? Once I Join() a thread, I can't restart it. So how can I start a thread and make it pause whenever the button 'pause' is pressed, and resume it when resume button is pressed?

The only thing this thread does, is show some random text in a label control.

Answer

Johannes Egger picture Johannes Egger · May 6, 2012

Maybe the ManualResetEvent is a good choice. A short example:

private static EventWaitHandle waitHandle = new ManualResetEvent(initialState: true); 

// Main thread
public void OnPauseClick(...) {
   waitHandle.Reset();
}

public void OnResumeClick(...) {
   waitHandle.Set();
}

// Worker thread
public void DoSth() {
   while (true) {
     // show some random text in a label control (btw. you have to
     // dispatch the action onto the main thread)
     waitHandle.WaitOne(); // waits for the signal to be set
   }
}