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.
sleep() method can be used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can't be negative, else it throws IllegalArgumentException .
Java Thread resume() methodThe resume() method of thread class is only used with suspend() method. This method is used to resume a thread which was suspended using suspend() method. This method allows the suspended thread to start again.
You can pause a thread by making it wait on a std::mutex .
You can suspend the calling thread for a given time in Python using the sleep method from the time module. It accepts the number of seconds for which you want to put the calling thread on suspension for.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With