Home / Forums / Preventing Cancellation Token Leaks with CancellationTokenSource Pooling in .NET 6+

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Tutorial

Preventing Cancellation Token Leaks with CancellationTokenSource Pooling in .NET 6+

AsyncMaster
Concurrency Geek
MEMBER
Rep: 72
Join Date: Jul 2020
Posts: 13
Thanks: 83
2y ago · May 11, 2024 4:05 PM
#1
In high-frequency web servers handling 20,000 requests per second, creating
CODE
new CancellationTokenSource(TimeSpan.FromSeconds(5))
on every request creates massive timer allocations.

In .NET 6+, use
CODE
CancelAfter
on a pooled or reused instance:


CSHARP
public async Task<HttpResponseMessage> SendWithTimeoutAsync(HttpClient client, HttpRequestMessage request)
{
    using var cts = new CancellationTokenSource();
    cts.CancelAfter(TimeSpan.FromSeconds(3)); // Reuses internal timer queue efficiently!

    return await client.SendAsync(request, cts.Token);
}


For Linked Tokens (
CODE
CreateLinkedTokenSource
):

Always dispose linked token sources immediately with
CODE
using
, otherwise the parent token maintains an event listener delegate in its internal registration list, causing a memory leak until the parent completes!
AsyncMaster · Concurrency Geek
Task Parallel Library (TPL), async/await internals, and lock...
The following users thanked AsyncMaster for this post:
CSharpNinja
Senior .NET Developer
VIP
Rep: 329
Join Date: Jan 2020
Posts: 16
Thanks: 75
2y ago · May 11, 2024 7:20 PM
#2
The linked token source leak is one of the most common memory leaks in long-running C# services. If the parent token is an app-lifetime token (
CODE
IHostApplicationLifetime.ApplicationStopping
), every undisposed child registration stays rooted in memory forever!
CSharpNinja · Senior .NET Developer
C# enthusiast, building distributed backend services and hig...
DevDan
.NET Core & Cloud
MEMBER
Rep: 324
Join Date: Feb 2021
Posts: 16
Thanks: 65
2y ago · May 13, 2024 3:20 AM
#3
In .NET 8, they also optimized
CODE
CancellationTokenSource
internals to use lock-free timer wheels, cutting timer registration overhead by half.
DevDan · .NET Core & Cloud
Writing clean C# code and microservices since .NET Core 2.1....