© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
28 replies
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
}

}
// 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
TrySetResult
?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Must create DependencySource on same Thread as the DependencyObject
C#CC# / help
3y ago
Entity Framework One-To-One [Answered]
C#CC# / help
4y ago
Why all my randoms are the same? [Answered]
C#CC# / help
4y ago