我有一个按钮点击事件继续:
private void button3_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
{
button2.Enabled = true;
button3.Enabled = false;
}
else
{
backgroundWorker1.RunWorkerAsync();
button2.Enabled = true;
button3.Enabled = false;
}
}
暂停按钮点击事件:
private void button2_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
backgroundWorker1.CancelAsync();
button3.Enabled = true;
soundPlay = false;
stop_alarm = true;
}
}
问题在于button3点击事件,继续代码有时后台很忙,所以我可以启用false / true按钮,但后台工作人员继续工作。 我想暂停DoWork事件并继续。
这是我的DoWork活动:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (true)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
if (tempCpuValue >= (float?)numericUpDown1.Value || tempGpuValue >= (float?)numericUpDown1.Value)
{
soundPlay = true;
blinking_label();
}
else
{
soundPlay = false;
}
cpuView();
gpuView();
Thread.Sleep(1000);
}
}
}
答案 0 :(得分:2)
您可以使用Thread
代替BackgroundWorker
吗?
使用Thread,在其工作子例程中,您可以将线程置于捕获ThreadInterruptedException
的try / catch块内的无限睡眠中。因此,当它循环遍历其正在处理的任何内容时,您可以查看布尔标志的值以了解是否要休眠,然后调用Thread.Sleep(Timeout.Infinite)
。当您捕获ThreadInterruptedException
时,将标志设置为false并继续执行。
要从您的UI恢复线程,您可以将'pause'标志设置为false并在您的线程上调用workerThread.Interrupt()
(假设您将其称为workerThread,即)。
来自here
的想法答案 1 :(得分:0)
您可能需要等到取消完成后再启用/禁用按钮。
private AutoResetEvent _resetEvent = new AutoResetEvent(false);
private void button2_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
backgroundWorker1.CancelAsync();
//Wait statement goes here.
this.Cursor=Cursors.AppStarting;
_resetEvent.WaitOne(); // will block until _resetEvent.Set() call made
button3.Enabled = true;
soundPlay = false;
stop_alarm = true;
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (true)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
if (tempCpuValue >= (float?)numericUpDown1.Value || tempGpuValue >= (float?)numericUpDown1.Value)
{
soundPlay = true;
blinking_label();
}
else
{
soundPlay = false;
}
cpuView();
gpuView();
Thread.Sleep(1000);
}
}
_resetEvent.Set(); // signal that worker is done
}