C#:如何暂停线程并在某些事件发生时继续?
如何暂停线程并在某些事件发生时继续?
我希望当按钮单击时线程继续。 有人告诉说thread.suspend不是暂停线程的正确方法。 那另一个解决方案
您可以使用System.Threading.EventWaitHandle 。
EventWaitHandle会阻塞,直到发出信号。 在您的情况下,它将通过按钮单击事件发出信号。
private void MyThread() { // do some stuff myWaitHandle.WaitOne(); // this will block until your button is clicked // continue thread }
您可以像这样发出等待句柄的信号:
private void Button_Click(object sender, EventArgs e) { myWaitHandle.Set(); // this signals the wait handle and your other thread will continue }
实际上,暂停一个线程是不好的做法,因为你很少知道线程当时正在做什么。 让线程运行通过ManualResetEvent
,每次都调用WaitOne()
是更可预测的。 这将作为一个门 – 控制线程可以调用Reset()
来关闭门(暂停线程,但安全),并使用Set()
来打开门(恢复线程)。
例如,您可以在每次循环迭代开始时调用WaitOne
(如果循环太紧,则每n
次迭代WaitOne
一次)。
你也可以尝试一下
private static AutoResetEvent _wait = new AutoResetEvent(false); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; backgroundWorker1.RunWorkerAsync(); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { Dosomething(); } private void Dosomething() { //Your Loop for(int i =0;i<10;i++) { //Dosomething _wait._wait.WaitOne();//Pause the loop until the button was clicked. } } private void btn1_Click(object sender, EventArgs e) { _wait.Set(); }