So I have a background worker that may still be working when the closing event occurs.
I call cancelasync() like so:
void ProgressDialog_Closing(object sender, CancelEventArgs e)
{
if (_worker.IsBusy)
{
//notifies the async thread that a cancellation has been requested.
_worker.CancelAsync();
}
}
However, I am getting a crash because of my runworker_completed method, which states that the dialog result cannot be set when the dialog box is not open. How can I check if the dialog box is still open?
void _worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (!Dispatcher.CheckAccess())
{
//run on UI thread
RunWorkerCompletedEventHandler handler = _worker_RunWorkerCompleted;
Dispatcher.Invoke(handler, null, DispatcherPriority.SystemIdle, new object[] { sender, e });
return;
}
else
{
if (e.Error != null)
{
error = e.Error;
}
else if (!e.Cancelled)
{
//assign result if there was neither exception nor cancel
result = e.Result;
}
ProgressBar.Value = ProgressBar.Maximum;
CancelButton.IsEnabled = false;
//set the dialog result, which closes the dialog
if (error == null && !e.Cancelled)
{
DialogResult = true;
}
else
{
DialogResult = false;
}
}
}
Constructor is nothing special, the runworkerthread is what starts the worker and sets the delegate to run.
public bool RunWorkerThread(object argument, Func<object> workHandler)
{
//store reference to callback handler and launch worker thread
workerCallback = workHandler;
_worker.RunWorkerAsync(argument);
return ShowDialog() ?? false;
}