how to pause/resume a thread

c#, multithreading, resume, wpf

Solution

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
   }
}

Problem

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.

Original source

Related problems