Pri*_*ief 17 c# multithreading wait
如何暂停线程并在某些事件发生时继续?
我希望线程在单击按钮时继续.有人告诉thread.suspend不是暂停线程的正确方法.那另一个解决方案
Mar*_*lon 19
您可以使用System.Threading.EventWaitHandle.
EventWaitHandle会阻塞,直到发出信号.在您的情况下,它将通过按钮单击事件发出信号.
private void MyThread()
{
// do some stuff
myWaitHandle.WaitOne(); // this will block until your button is clicked
// continue thread
}
Run Code Online (Sandbox Code Playgroud)
你可以像这样发信号给你的等待句柄:
private void Button_Click(object sender, EventArgs e)
{
myWaitHandle.Set(); // this signals the wait handle and your other thread will continue
}
Run Code Online (Sandbox Code Playgroud)
事实上,挂起线程是不好的做法,因为你很少知道究竟什么是线程的时候做.让线程经过a ManualResetEvent,WaitOne()每次调用都更容易预测.这将作为一个门 - 控制线程可以调用Reset()关闭门(暂停线程,但安全),并Set()打开门(恢复线程).
例如,您可以WaitOne在每次循环迭代的开始时调用(或者n如果循环太紧,则每次迭代调用一次).