C#C
C#4y ago
Dusty

TaskCompletionSource.SetResult() executes on the same thread as the waiting one [Answered]

Hey, as the title already says I've found a deadlock in my code and would like to understand it.
To give you an example:
// Called from Thread Id 1
await SomeMethodAsync();
// Continues on Thread Id 5

// await Task.Yield() - fixes the issue

Console.ReadKey();  // example to block the thread

class Sample
{

Task SomeMethodAsync()
{
  var tcs = new TaskCompletionSource();
  queue.Enqueue(tcs);
  return tcs.Task;
}

void OnMessage()
{
  // Called from Thread Id 5
  var tcs = queue.Dequeue();
  tcs.TrySetResult();  // Blocks the whole event loop

  // Do some other stuff
}

}


So why is the awaited method continuing on the thread that called TrySetResult ?
Was this page helpful?