Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Fix a TaskCompletionSource Deadlock Caused by a Continuation That Runs Synchronously on the Thread Calling SetResult

- 15.10.26 - ErcanOPAK

🔧 The TaskCompletionSource That Deadlocked Its Own Caller

A plain TaskCompletionSource<T> runs every continuation chained onto its Task synchronously, on whatever thread happens to call SetResult – by default, that’s not a background detail, it’s the thread that just finished the work you’re wrapping. If that continuation then tries to acquire a lock the calling code is still holding, or blocks waiting on something that thread also owns, you get a deadlock that only appears under contention.

🔎 The Problem

private readonly object _lock = new object();
private TaskCompletionSource<int> _pendingResult;

public void OnHardwareCallback(int value)
{
    lock (_lock)
    {
        // SetResult runs every awaiter's continuation
        // synchronously, right here, before this method
        // returns - while _lock is still held.
        _pendingResult?.SetResult(value);
    }
}

public async Task<int> WaitForNextValueAsync()
{
    var tcs = new TaskCompletionSource<int>();
    _pendingResult = tcs;
    int result = await tcs.Task;

    lock (_lock) // Deadlock: the continuation above already
    {             // tried to re-enter this same lock.
        // ...
    }
    return result;
}

✅ Fix: Force Continuations Off the Calling Thread

  • Construct it with new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously) – this is the single flag that moves every continuation onto a thread-pool thread instead of running it inline inside SetResult, and it should be the default choice unless you’ve specifically measured that synchronous completion is safe.
  • Never call SetResult (or SetException/SetCanceled) while holding a lock the continuation might also need – even with RunContinuationsAsynchronously set, it’s a fragile pattern that becomes a real deadlock the moment someone changes the continuation’s code later.
  • If you’re on an older target that predates the option, wrap the call in Task.Run(() => tcs.SetResult(value)) to get the same effect – it costs a thread-pool hop, but it’s cheap insurance against a deadlock that only shows up under production load.

🚨 Why This Is Dangerous in Production

  • The deadlock depends on timing and lock contention, so it can pass every test and every staging run and only reproduce under real concurrent load – exactly the conditions you can’t easily attach a debugger to.
  • It’s not unique to a hand-rolled TaskCompletionSource either – any library that exposes one under the hood (a custom async wrapper around a callback-based API, a manual connection pool) inherits the same synchronous-continuation risk unless it was built with the flag set.

A TaskCompletionSource doesn’t ask whose thread it’s running on – it just runs there, and if that thread is still holding a lock your continuation needs, you’ve built a deadlock with no waiting involved.

— C# Best Practice

Related posts:

C#: Use Null-Coalescing Operator (??) for Default Values

C#: Use Null-Coalescing Operator (??) for Default Values

C# LINQ Looks Clean but Allocates Heavily

C# LINQ Looks Clean but Allocates Heavily

C#: Fix String.Format Silently Misaligning Columns Because the {0,10} Padding Counts Characters, Not...

C#: Fix String.Format Silently Misaligning Columns Because the {0,10} Padding Counts Characters, Not...

Views: 12

Post navigation

CSS: Fix a Subgrid That Ignores Its Parent Grid’s Track Sizes Because display: subgrid Was Only Set on One Axis
JavaScript: Fix a Generator Function Return Value That Gets Silently Ignored Unless You Read It From the Final done Result

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com