title: How do I implement InvokeRequired UI pattern inside an async method?
body: <p>Let's say I have a <code>Form</code> that tries to deal with a multi-threaded environment; it therefore checks if it's running on the UI thread before any UI modification is done:</p>
  
  <pre><code>partial class SomeForm : Form
  {
      public void DoSomethingToUserInterface()
      {
          if (InvokeRequired)
          {
              BeginInvoke(delegate { DoSomethingToUserInterface() });
          }
          else
          {
              … // do the actual work (e.g. manipulate the form or its elements)
          }
      }
  }
  </code></pre>
  
  <p>Now let's say I am performing some lengthy operation inside the <code>…</code> part of that method; I'd therefore like to make it asynchronous using <code>async/await</code>.</p>
  
  <p>Given that I should change the method signature to return a <code>Task</code> instead of <code>void</code> (so that exceptions can be caught), how would I implement the part that performs the <code>BeginInvoke</code>? What should it return?</p>
  
  <pre><code>public async Task DoSomethingToUserInterfaceAsync()
  {
      if (InvokeRequired)
      {
          // what do I put here?
      }
      {
          … // like before (but can now use `await` expressions)
      }
  }
  </code></pre>