title: Synchronous or asynchronous continuation upon TaskCompletionSource.TrySetResult?
body: <p>How to tell if the continuation initiated by <a href="http://msdn.microsoft.com/en-us/library/dd449176%28v=vs.110%29.aspx" rel="nofollow"><code>TaskCompletionSource.TrySetResult</code></a> is going to be executed synchronously or asynchronously? </p>
  
  <p>For example:</p>
  
  <pre><code>// class A
  
  void RegisterNotification(TaskCompletionSource&lt;object&gt; tcs)
  {
      this.source.NotificationEvent += (s, eData) =&gt; 
      {
          Debug.WriteLine("A.before");
          tcs.TrySetResult(eData.Result);
          Debug.WriteLine("A.after");
  
          DoProcessingA();
      };   
  }
  
  // class B
  
  async Task RequestNotificationAsync()
  {
      var tcs = new TaskCompletionSource&lt;object&gt;();
      this.a.RegisterNotification(tcs);    
  
      Debug.WriteLine("B.before");
      var data = await tcs.Task;
      Debug.WriteLine("B.after");
  
      DoProcessingB();
  }
  </code></pre>
  
  <p>If <code>NotificationEvent</code> is fired on a thread with the different synchronization context from that of where <code>await tcs.Task</code> took place, the debug output will be:</p>
  
  <pre>
  B.before
  <b>A.before</b>
  <b>A.after</b>
  B.after
  </pre>
  
  <p>That is, the <code>await tcs.Task</code> continuation is executed asynchronously. If it is fired on the same synchronization context (or if there is no synchronization context in both places), the output will be:</p>
  
  <pre>
  B.before
  <b>A.before</b>
  B.after
  <b>A.after</b>
  </pre>
  
  <p>That is, the continuation is executed synchronously.</p>
  
  <p>Is there a way to predict this order inside <code>RegisterNotification</code>?</p>
  
  <p>I could save <code>SynchronizationContext.Current</code> inside <code>RegisterNotification</code> and compare it later when I call <code>tcs.TrySetResult</code>. But that not necessarily mean that <code>await tcs.Task</code> will take place on the context I saved. </p>
  
  <p>In theory, if I could predict this, I might be able to use it to diagnose and prevent potential deadlocks.</p>