When I try exactly that in my code, it doesn't cause a problem.
BackgroundWorker bw;
private void button1_Click(object sender, EventArgs e)
{
bw = new BackgroundWorker();
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerAsync();
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
int i = 0;
while (true)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
Console.WriteLine(i++);
System.Threading.Thread.Sleep(500);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
DialogResult result = MessageBox.Show("Are you sure you want to stop broadcast?", "Confirm", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
System.GC.Collect();
if (bw.IsBusy)
{
bw.CancelAsync();
}
}
}
catch (Exception ex)
{
Console.WriteLine("Button Stop : " + ex.StackTrace);
}
}
So, either the problem is in your background worker code, or your button handler is not being called on the UI thread.
Some questions:
Why are you explicitly calling the Garbage Collector before you try to stop the worker? Ignoring "why are you calling the GC at all", surely any GC would be better done once the worker is dead and it's resources released?
What is the worker actually doing?