I have a button click event for continue:
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;
}
}
And a button click event for pausing:
private void button2_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
backgroundWorker1.CancelAsync();
button3.Enabled = true;
soundPlay = false;
stop_alarm = true;
}
}
The problem is with the button3 click event the continue code sometimes the background is busy so i can enable false/true the buttons but the backgroundworker is keep working.
I want to pause the DoWork event and to continue.
This is my DoWork event:
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);
}
}
}
You could do this with a
Threadinstead of aBackgroundWorker?With a Thread, in its working subroutine you could put the thread into an infinite sleep inside a try/catch block that catches
ThreadInterruptedException. So, as it loops through whatever it’s working on, you could look at the value of a boolean flag to know whether or not to sleep, and then callThread.Sleep(Timeout.Infinite). When you catchThreadInterruptedExceptionyou set the flag to false and continue to execute.To make the thread resume from your UI, you would set the ‘pause’ flag to false and call
workerThread.Interrupt()on your thread (assuming you called it workerThread, that is).Idea sourced from here