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 CancellationTokenSource.CancelAfter Timer That Never Fires Because the Source Was Disposed Too Early

- 11.10.26 - ErcanOPAK

🔧 The CancelAfter Timer That Never Gets a Chance to Fire

CancellationTokenSource.CancelAfter schedules an internal timer that calls Cancel once its delay elapses, but that timer belongs entirely to the CancellationTokenSource instance that scheduled it. Disposing the source before the delay elapses tears the timer down along with everything else the source owns, so the scheduled cancellation silently never happens. Any operation still waiting on that source’s token keeps waiting exactly as long as it would have without a timeout at all, because the mechanism meant to cut it off was dismantled before it ever got the chance to run.

🔎 The Problem

async Task<string> CallWithTimeoutAsync(HttpClient client, string url)
{
    using var cts = new CancellationTokenSource();
    cts.CancelAfter(TimeSpan.FromSeconds(30));

    // An earlier guard clause returns before the actual call - e.g.
    // a cache hit short-circuits the method entirely:
    if (TryGetCached(url, out var cached))
        return cached; // 'using' disposes cts HERE, cancelling nothing

    // If we DO reach this line, the CancelAfter timer is still fine -
    // the bug only bites on the early-return path, intermittently.
    return await client.GetStringAsync(url, cts.Token);
}

✅ Fix: Create and Dispose the Source Right Around the Call It Times

  • Create the CancellationTokenSource, and call CancelAfter, only immediately before the specific operation it’s meant to time out – not earlier in the method, where an unrelated early return can dispose the source before the timed call has even started.
  • When a timeout token has to be combined with an already-existing one, use CancellationTokenSource.CreateLinkedTokenSource and keep that linked source alive for the whole duration of the awaited call, disposing it in a finally block placed right after the await rather than relying on a using declared several lines above a possible early exit.
  • Make reviewing every path between a CancelAfter call and the operation it times a habit: any return, throw, or continue on that path can dispose the source early on a path that looks completely unrelated to timeouts.

⚠️ Why This Is Easy to Miss

  • The bug is entirely path-dependent: the common, fast path – the early return – is exactly the one that disposes the timer early, while the slower path that actually needs the timeout is the one least often exercised during testing.
  • Nothing throws when this happens – CancelAfter on a source that gets disposed before its delay elapses simply never gets the chance to run its timer callback, so the operation just hangs for however long the underlying call’s own default timeout, if it has one at all, happens to take, which is often far longer than the 30 seconds that was intended.

A cancellation you schedule and then dispose before it can fire was never actually scheduled at all.

— C# Best Practice

Related posts:

C#: Fix a Task's .Result Property That Throws an AggregateException Instead of the Original Exceptio...

C#: Fix a Task's .Result Property That Throws an AggregateException Instead of the Original Exceptio...

Display HTPP Headers in C# & ASP.net

Display HTPP Headers in C# & ASP.net

C# LINQ Looks Clean but Allocates Heavily

C# LINQ Looks Clean but Allocates Heavily

Views: 7

Post navigation

Photoshop: Fix Content-Aware Fill That Silently Pulls From the Wrong Background Because the Sampling Area Ring Was Never Adjusted
Windows 11: Fix Windows Hello Fingerprint Sign-In That Quietly Falls Back to PIN Only Because a Driver Update Reset It

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 (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (976)
  • Get the First and Last Word from a String or Sentence in SQL (857)
  • How to select distinct rows in a datatable in C# (852)
  • 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 @ (607)
  • Average of all values in a column that are not zero in SQL (569)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (546)
  • 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 (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (976)
  • Get the First and Last Word from a String or Sentence in SQL (857)
  • How to select distinct rows in a datatable in C# (852)

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