[英]C# : How to pause the thread and continue when some event occur?
How can I pause a thread and continue when some event occur? 如何暂停线程并在某些事件发生时继续?
I want the thread to continue when a button is clicked. 我希望线程在单击按钮时继续。 Someone told me that
thread.suspend
is not the proper way to pause a thread. 有人告诉我
thread.suspend
不是暂停线程的正确方法。 Is there another solution? 还有其他解决方案吗?
You could use a System.Threading.EventWaitHandle . 您可以使用System.Threading.EventWaitHandle 。
An EventWaitHandle blocks until it is signaled. EventWaitHandle会阻塞,直到发出信号。 In your case it will be signaled by the button click event.
在您的情况下,它将通过按钮单击事件发出信号。
private void MyThread()
{
// do some stuff
myWaitHandle.WaitOne(); // this will block until your button is clicked
// continue thread
}
You can signal your wait handle like this: 你可以像这样发信号给你的等待句柄:
private void Button_Click(object sender, EventArgs e)
{
myWaitHandle.Set(); // this signals the wait handle and your other thread will continue
}
Indeed, suspending a thread is bad practice since you very rarely know exactly what a thread is doing at the time. 事实上,挂起线程是不好的做法,因为你很少知道到底是什么一个线程在时间做。 It is more predictable to have the thread run past a
ManualResetEvent
, calling WaitOne()
each time. 让线程运行通过
ManualResetEvent
,每次都调用WaitOne()
是更可预测的。 This will act as a gate - the controlling thread can call Reset()
to shut the gate (pausing the thread, but safely), and Set()
to open the gate (resuming the thread). 这将作为一个门 - 控制线程可以调用
Reset()
来关闭门(暂停线程,但安全),并使用Set()
来打开门(恢复线程)。
For example, you could call WaitOne
at the start of each loop iteration (or once every n
iterations if the loop is too tight). 例如,您可以在每次循环迭代开始时调用
WaitOne
(如果循环太紧,则每n
次迭代WaitOne
一次)。
You can try this also 你也可以尝试一下
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.