I am writing a windows application that runs a sequence of digital IO actions repeatedly.
This sequence of actions starts when the user click a "START" button, and it is done by a background worker in backgroundWorker1_DoWork().
However, there are occasions when I get the "This backgroundworker is currently busy......." error message.
I am thinking of implementing the following in the code, by using a while loop to "kill" the background worker before starting another sequence of action:
if (backgroundWorker1.IsBusy == true)
{
backgroundWorker1.CancelAsync();
while (backgroundWorker1.IsBusy == true)
{
backgroundWorker1.CancelAsync();
}
backgroundWorker1.Dispose();
}
backgroundWorker1.RunWorkerAsync();
I think my main concern is, will the backgroundWorker1 be "killed" eventually? If it will, will it take a long time to complete it?
Will this coding get me into an infinite loop?
You can use something like this (for more information about aborting managed threads and about ThreadAbortException see "Plumbing the Depths of the ThreadAbortException Using Rotor" by Chris Sells):
public class AbortableBackgroundWorker : BackgroundWorker
{
private Thread workerThread;
protected override void OnDoWork(DoWorkEventArgs e)
{
workerThread = Thread.CurrentThread;
try
{
base.OnDoWork(e);
}
catch (ThreadAbortException)
{
e.Cancel = true; //We must set Cancel property to true!
Thread.ResetAbort(); //Prevents ThreadAbortException propagation
}
}
public void Abort()
{
if (workerThread != null)
{
workerThread.Abort();
workerThread = null;
}
}
}
Usage:
backgroundWorker1 = new AbortableBackgroundWorker();
//...
backgroundWorker1.RunWorkerAsync();
if (backgroundWorker1.IsBusy == true)
{
backgroundWorker1.Abort();
backgroundWorker1.Dispose();
}