如何暂停/恢复线程 [英] how to pause/resume a thread

查看:158
本文介绍了如何暂停/恢复线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能暂停/恢复线程?有一次,我加入()一个线程,我不能重新启动它。
那么,如何可以启动一个线程,并使其暂停每当按钮暂停被按下,并恢复它当按下恢复按钮?

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.

推荐答案

也许 ManualResetEvent的是一个不错的选择。
简单例子:

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

// Main thread:
// boolean parameter whether to set the initial state to signaled.
private static ManualResetEvent event = new ManualResetEvent(true); 

public void OnPauseClick(...) {
   event.Reset();
}

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

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

这篇关于如何暂停/恢复线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆