title: What is the best way of ensuring that an async method can update a non-threadsafe collection?
body: <p>I'm doing async calls that eventually will update a collection in the GUI. The async call is done from a delegate command like this: </p>
  
  <pre><code>StartDoingUsefulStuffCommand = new DelegateCommand(() =&gt; Task.Run(() =&gt; StartDoingUsefulStuff()));
  
  public async Task StartDoingUsefulStuff()
  {
      try
      {
          await some method
          do something else
          MyCollection.Clear();
          ...
          ...
      }
      catch (Exception e)
      {
         // handle exception
      }
  }
  </code></pre>
  
  <p>Eventually the StartDoingUsefulStuff method wants to update a collection, resulting in this exception because another thread tries to update a collection:</p>
  
  <blockquote>
    <p>A first chance exception of type 'System.NotSupportedException'
    occurred in PresentationFramework.dll</p>
    
    <p>Additional information: This type of CollectionView does not support
    changes to its SourceCollection from a thread different from the
    Dispatcher thread.</p>
  </blockquote>
  
  <p>I've found one solution: Run the task in the current SynchronizationContext: </p>
  
  <pre><code>Task.Factory.StartNew(() =&gt; StartDoingUsefulStuff(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
  </code></pre>
  
  <p>This will work fine, but to me it seems tedious to do all this stuff each time a command is called from XAML. What are your opinions on my present solution/what are best practices?</p>