简体   繁体   中英

Passing results back to main thread from a cancelled BackgroundWorker thread

How can I cancel a backgroundworker and pass back an error message. I know that you can use DoWorkEventArgs e.Results to pass back results to main thread but e.Results gets overwritten when I cancel the child thread. Example:

private MyProgram_DoWork(object sender, DoWorkEventArgs e)
{
     e.Cancel = true;
     e.Result = "my error message";
     return;
}

private void MyProgram_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
     if ((e.Cancelled == true))
     { 
            string ErrorMsg = (string)e.Result;   //exception happens here 

            ....
     }
     else
     { 
          // success code
     }
}

Is there another way to stop my child thread and send a string back to the main thread?

If your long-running process was canceled, it wouldn't really have a "result", as the process didn't completely finish.

According to the documentation :

Your RunWorkerCompleted event handler should always check the Error and Cancelled properties before accessing the Result property. If an exception was raised or if the operation was canceled, accessing the Result property raises an exception.

I took a peek inside BackgroundWorker . Here's the contents of the Result property:

public object Result
{
  get
  {
    this.RaiseExceptionIfNecessary();
    return this.result;
  }
}

And the contents of RaiseExceptionIfNecessary() :

protected void RaiseExceptionIfNecessary()
{
  if (this.Error != null)
    throw new TargetInvocationException(SR.GetString("Async_ExceptionOccurred"), this.Error);
  if (this.Cancelled)
    throw new InvalidOperationException(SR.GetString("Async_OperationCancelled"));
}

So if you cancel the thread, referencing Result will throw an InvalidOperationException . That's just the way it's designed.

I don't know what the "best" way is to pass a string back. I'd say you could define a variable in the same method you run the BackgroundWorker from, and assign a value to it from the DoWork event.

You just have to be very careful that nothing on the UI thread is somehow bound to the variable or you could run into problems. A string should be safe, but don't start adding to a list that's bound to a ComboBox or something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM