I have a background worker that performs a time consuming task, but I'm having trouble with the cancelling issue because I can manage to only flag cancellation and not actually terminate the process. In order to solve it, I tried to put some check points in the heavy function that I want to exit , but it seems not quite efficient. my code looks like this :
in some points in the heavy function I put those 2 lines :
if (general.backgroundWorker1.CancellationPending)
{
return;
}
private void button4_Click(object sender, EventArgs e) //button invokes heavy function
{
if (!backgroundWorker1.IsBusy)
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
heavyFunction(this);
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
}
private void backgroundWorker1_RunWorkerCompleted_1(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
statusLabel.Text = "Status: cancelled";
}
else if (e.Error != null)
{
statusLabel.Text = "ERROR!";
}
else
{
some code;
}
}
private void cancelSDoutLoop_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
}