Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

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

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
C#

C#: Fix a TaskCompletionSource Never Completing After a Timeout

- 29.11.26 - ErcanOPAK

🔧 Fix a TaskCompletionSource Never Completing After a Timeout

Bridging a callback-based API into async/await with a TaskCompletionSource works cleanly as long as something eventually calls SetResult or SetException on it, but a manual timeout built with Task.WhenAny(tcs.Task, Task.Delay(timeout)) only decides which task your own code moves on from first — it does nothing to the TaskCompletionSource itself. If the underlying callback-based operation has no cancellation support and never calls back at all, that TCS’s Task sits pending forever, kept alive by whatever’s still referencing it, even though your code has already logically moved on after the delay won the race.

🔎 The Problem

var tcs = new TaskCompletionSource<Result>();
legacyApi.BeginOperation(result => tcs.TrySetResult(result));

var winner = await Task.WhenAny(tcs.Task, Task.Delay(timeout));
if (winner != tcs.Task)
{
    // "Timed out" - but tcs.Task is still pending right now, and stays
    // pending forever if legacyApi's callback never actually fires;
    // nothing here ever calls SetException/SetCanceled on it

✅ Fix: A TaskCompletionSource Never Completing After a Timeout

  • Prefer `await tcs.Task.WaitAsync(timeout)` (available since .NET 6) over Task.WhenAny for this pattern — it throws a TimeoutException and, crucially, still leaves you a reference to handle the original task’s eventual completion instead of abandoning it silently.
  • Register a CancellationToken callback that calls TrySetCanceled() (or TrySetException) on the TaskCompletionSource directly whenever the operation should be considered timed out, so the task itself actually completes instead of just being out-raced.
  • Always construct TaskCompletionSource with TaskCreationOptions.RunContinuationsAsynchronously, so a late completion from the legacy callback doesn’t synchronously run continuations on whatever thread happens to call SetResult.

🚨 Why This Is Dangerous

  • A TaskCompletionSource that never completes keeps its continuations and any captured state reachable for as long as something still holds a reference to it, which across enough “timed out” operations in a long-running service adds up to a slow, hard-to-diagnose memory leak.

Racing a timeout against a task decides which one you wait for — it was never going to decide whether the other one actually finishes.

— C# Best Practice

Related posts:

C# Encryption Done Right — AesGcm Instead of AES CBC

C# Encryption Done Right — AesGcm Instead of AES CBC

C#: Use Object Initializers for Clean Object Creation

C#: Use Object Initializers for Clean Object Creation

C#: Professional Formatting with Advanced String Interpolation

C#: Professional Formatting with Advanced String Interpolation

Views: 4
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

Asp.Net Core: Fix a Correlation Cookie Dropped by SameSite Lax
Kubernetes: Fix a Liveness Probe Restarting a Pod Mid-Migration

Leave a Reply Cancel reply

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

Most Read

  1. 01How to make theater mode the default for Youtube 1,079 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 996 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 995 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 866 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 671 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 629 views
  8. 08Average of all values in a column that are not zero in SQL 584 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 561 views
Bits of .NET

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

Social

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