I am working on a c# app. I want to use a background worker to make all my heavy processing, but I'd like to be able to stop it while running. The problem I face is that I can cancel it with "backgroundWorker1.CancelAsync()" but it doesn't stop right away.
Is there any way to instantly "kill" the thread ? Is it possible to stop the thread instantly after clicking instead of waiting the end of the current sleep ?
My code :
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 1; i <= 10; i++)
{
if (backgroundWorker1.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
System.Threading.Thread.Sleep(5000);
backgroundWorker1.ReportProgress(i * 10);
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
string prog = (e.ProgressPercentage.ToString() + "%");
Console.WriteLine(prog);
}
private void button26_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
private void button27_Click(object sender, EventArgs e)
{
Console.WriteLine(backgroundWorker1.IsBusy.ToString());
}
Thanks to anyone who helps me ^^