title: C# Background worker setting e.Result in DoWork and getting value back in WorkCompleted
body: <p>C# 2008 SP1</p>
  
  <p>I am using the background worker</p>
  
  <p>If one of the conditions fails I will set e.cancel to true, and assign the string to the e.result. Everything works there.</p>
  
  <p>However, when the workCompleted fires, I test for the e.Result and I get an exception "e.result throw an exception of type systeminvalidoperation".</p>
  
  <p>I guess I could use a global variable to set in the DoWork and compare in the work completed. But this might not be threadsafe. </p>
  
  <p>Can anyone tell me why I am getting this with the e.Result, and how can I solve this?</p>
  
  <p>Many thanks,</p>
  
  <pre><code>    private void bgwPrepareCall_DoWork(object sender, DoWorkEventArgs e)
      {
          // Check to see if the called number is blocked. 
          // If the nubmer is blocked display error message.
          if (this.IsNoGateway(sipUsername, statusDisplay1.PhoneNumber))
          {
              // this.SetIdleState(DialerErrorMessage.GetErrorDescription(12));
              e.Cancel = true;
              e.Result = "NoGateway";
              return;
          }
  
          if (!this.IsInvalidTelephoneNumber(sipUsername, statusDisplay1.PhoneNumber))
          {
              // this.SetIdleState(DialerErrorMessage.GetErrorDescription(13));
              e.Cancel = true;
              e.Result = "InvalidNumber";
              return;
          }
      }
  
      private void bgwPrepareCall_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
      {
          if (e.Error == null)
          {
              if (e.Cancelled)
              {
                  // Failed
                  switch (e.Result.ToString())
                  {
                      case "NoGateway":
                          Console.WriteLine("NoGateway: [ Failed ]");
                          break;
  
                      case "InvalidNumber":
                          Console.WriteLine("InvalidNumber: [ Failed ]");
                          break;
  
                      default:
                          Console.WriteLine("Unknown");
                          break;
                  }
              }
              if (!e.Cancelled)
              {
                  // Successfull
                  Console.WriteLine("NoGateway: [ ok ]");    
                  Console.WriteLine("InvalidNumber: [ ok ]");
              }
          }
          else
          {
              Console.WriteLine("PrepareCall Failed: [ " + e.Error.Message + " ]");
          }
      }
  </code></pre>