i have a serious problem with background worker. code is working if task is ending regular. when i cancel the background task i get an system.invalidoperationexception in the RunWorkerCompleted function for e.Result. what is wrong? thank you.
here is my cod:
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
if (backgroundWorker.CancellationPending == true)
e.Cancel = true;
e.Result = resultList;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
List<Object> resultList = (List<Object>)e.Result;
}
BackgroundWorker makes the implementation of threads in Windows Forms. Intensive tasks need to be done on another thread so the UI does not freeze. It is necessary to post messages and update the user interface when the task is done.
This is by design, the Result property getter will throw when DoWork was cancelled or threw an exception. Simply check for that:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (!e.Cancelled && e.Error == null) {
List<Object> resultList = (List<Object>)e.Result;
// etc..
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With