如何暂停/恢复线程?一旦我 Join()
一个线程,我就无法重新启动它。
那么我怎样才能启动一个线程并在按下“暂停”按钮时使其暂停,并在按下恢复按钮时恢复它呢?
这个线程做的唯一一件事就是在标签控件中显示一些随机文本。
最佳答案
也许 ManualResetEvent
是一个不错的选择。
一个简短的例子:
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
}
}
关于c# - 如何暂停/恢复线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10469687/