title: How do you run on the STA thread when using a Task
body: <p>I'm developing a VSTO Outlook add-in in VS2010. In the <code>ThisAddIn_Startup</code> method (which is called when the addin starts) my code needs to check if Outlook is running on the company network or not. If Outlook isn't running on the network it takes about 3 seconds to come back with the answer. So I wrapped the code up in a Task to make it run Async to ensure it doesn't hang Outlook while it's checking.</p>
  
  <p>e.g.</p>
  
  <pre><code>bool onNetwork = false;
  Task task = Task.Factory.StartNew(() =&gt;
  {
      onNetwork = IsConnectedToNetwork();
  });
  </code></pre>
  
  <p>After it's finished checking it needs to load and display the relevant Form. 
  So I changed the code to:</p>
  
  <pre><code>Task task = Task.Factory.StartNew(() =&gt;
  {
      if (IsConnectedToNetwork())
      {
          OnNetworkForm onNetworkForm = new OnNetworkForm();
          onNetworkForm.Show();
      }
      else
      {
          OffNetworkForm offNetworkForm = new OffNetworkForm();
          offNetworkForm.Show();
      }
  });
  </code></pre>
  
  <p>But the Forms need to be loaded on the UI Thread. Otherwise I get an <code>InvalidOptionationException</code> when it tries to load and show the forms with the message:</p>
  
  <blockquote>
    <p>The calling thread must be STA, because many UI components require
    this.</p>
  </blockquote>
  
  <p>My question is how can I make the forms load on the UI Thread?</p>
  
  <p><strong>Please note</strong> </p>
  
  <p>I can't use await as that's C# 5.0 and VS 2010 doesn't support C# 5.0. 
  And the ThisAddin class isn't a control and therefore doesn't have the <code>BeginInvoke</code> or <code>Invoke</code> methods available.</p>