title: How to call a function in a backgroundworker thread that is to be completed on the main UI thread?
body: <p>I am using a <code>BackgroundWorker</code> to monitor if a bit has flipped on an external device every couple of seconds. I then want it to call a function that is to be run on the main UI thread, but is instead being run on the same thread as the <code>BackgroundWorker</code>. This is a problem because I am getting errors about the application interface being marshaled on a different thread.</p>
  
  <p>Currently when I call the function from the <code>BackgroundWorker</code> thread it is be computed on the same thread as the <code>BackgroundWorker</code>.</p>
  
  <pre><code>private void Task1()
  {
      //Function does work before calling backgroundworker
      BackGroundWorker.RunWorkerAsync();
  }
  
  private async void BackGroundWorker_DoWork(object sender, DoWorkEventArgs e)
  {
      //Monitor for bit being flipped on external device
      Task2();
  }
  
  private void Task2()
  {
      //Work to be completed after the bit has been flipped
  }
  </code></pre>
  
  <p>I'm expecting that once the bit has been detected to have flipped, the <code>BackgroundWorker</code> thread calls the function to be completed on the main UI thread. </p>
  
  <p>What has actually been happening is that I get the following error because the function is being run on the same thread as the <code>BackgroundWorker</code>:</p>
  
  <blockquote>
    <p>The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))</p>
  </blockquote>