Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cancel background worker exception in e.result

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;
} 
like image 1000
user1069951 Avatar asked Nov 28 '11 18:11

user1069951


People also ask

What is BackgroundWorker C#?

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.


1 Answers

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..
    }
} 
like image 145
Hans Passant Avatar answered Oct 23 '22 03:10

Hans Passant