title: Nested Task - The current synchronizationcontext may not be used as a taskscheduler
body: <p>I've got a WPF MVVM application which has the concept of "services". </p>
  
  <p>Each service method gets passed a callback as on of the parameters, it creates the <code>Task</code>, does the work and then calls the callback in the ViewModel in the continuation.</p>
  
  <p>In one of my service methods the "work" involves synchronising databases and then loading the updated database from the DB. Another method counts the number of records in a table. Here are some simplified examples.</p>
  
  <pre><code>public void GetStudents(Action&lt;IEnumerable&lt;Student&gt;&gt; callback)
  {
      Task.Run(() =&gt; 
      {
            Sync();
            return students;
      }).ContinueWith(task =&gt;
      {
            callback(task.Result);
      }, TaskScheduler.FromCurrentSynchronizationContext());
  }
  public void CountStudents(Action&lt;int&gt; callback)
  {
      Task.Run(() =&gt; 
      {
          return students.Count();
      }).ContinueWith(task =&gt; 
      {
          callback(task.Result);
      }, TaskScheduler.FromCurrentSynchronizationContext());
  }
  </code></pre>
  
  <p>These methods were called separately from different ViewModels and they worked as expected; however (isn't there always a however) I've added an event on synchronisation completed using the Prism <code>EventAggregator</code>. When sync has completed, if the Student table has been update I want to re-run the count method. The problem is because this is happening from the context of the other Task I'm getting this exception.</p>
  
  <blockquote>
    <p>"The current synchronizationcontext may not be used as a taskscheduler"</p>
  </blockquote>
  
  <p>I've tried joining the Task to the parent task with <code>TaskCreationOptions.AttachedToParent</code> but that doesn't fix the issue.</p>
  
  <p>The more I think about it I think I should move the <code>Task</code> creation to my ViewModels, it seems the most logical and correct place for it to be, but is there something I'm missing that means I don't have to do that in this instance?</p>