title: When correctly use Task.Run and when just async-await
body: <p>I would like to ask you on your opinion about the correct architecture when to use <code>Task.Run</code>. I am experiencing laggy UI in our WPF .NET 4.5
  application (with Caliburn Micro framework).</p>
  
  <p>Basically I am doing (very simplified code snippets):</p>
  
  <pre><code>public class PageViewModel : IHandle&lt;SomeMessage&gt;
  {
     ...
  
     public async void Handle(SomeMessage message)
     {
        ShowLoadingAnimation();
  
        // Makes UI very laggy, but still not dead
        await this.contentLoader.LoadContentAsync();
  
        HideLoadingAnimation();
     }
  }
  
  public class ContentLoader
  {
      public async Task LoadContentAsync()
      {
          await DoCpuBoundWorkAsync();
          await DoIoBoundWorkAsync();
          await DoCpuBoundWorkAsync();
  
          // I am not really sure what all I can consider as CPU bound as slowing down the UI
          await DoSomeOtherWorkAsync();
      }
  }
  </code></pre>
  
  <p>From the articles/videos I read/saw, I know that <code>await</code> <code>async</code> is not necessarily running on a background thread and to start work in the background you need to wrap it with await <code>Task.Run(async () =&gt; ... )</code>. Using <code>async</code> <code>await</code> does not block the UI, but still it is running on the UI thread, so it is making it laggy.</p>
  
  <p>Where is the best place to put Task.Run?</p>
  
  <p>Should I just</p>
  
  <ol>
  <li><p>Wrap the outer call because this is less threading work for .NET</p></li>
  <li><p>, or should I wrap only CPU-bound methods internally running with <code>Task.Run</code> as this makes it reusable for other places? I am not sure here if starting work on background threads deep in core is a good idea.</p></li>
  </ol>
  
  <p>Ad (1), the first solution would be like this:</p>
  
  <pre><code>public async void Handle(SomeMessage message)
  {
      ShowLoadingAnimation();
      await Task.Run(async () =&gt; await this.contentLoader.LoadContentAsync());
      HideLoadingAnimation();
  }
  
  // Other methods do not use Task.Run as everything regardless
  // if I/O or CPU bound would now run in the background.
  </code></pre>
  
  <p>Ad (2), the second solution would be like this:</p>
  
  <pre><code>public async Task DoCpuBoundWorkAsync()
  {
      await Task.Run(() =&gt; {
          // Do lot of work here
      });
  }
  
  public async Task DoSomeOtherWorkAsync(
  {
      // I am not sure how to handle this methods -
      // probably need to test one by one, if it is slowing down UI
  }
  </code></pre>