2y ago · May 11, 2024 4:05 PM
In high-frequency web servers handling 20,000 requests per second, creating on every request creates massive timer allocations.
In .NET 6+, use on a pooled or reused instance:
For Linked Tokens ():
Always dispose linked token sources immediately with, otherwise the parent token maintains an event listener delegate in its internal registration list, causing a memory leak until the parent completes!
CODE
new CancellationTokenSource(TimeSpan.FromSeconds(5))In .NET 6+, use
CODE
CancelAfter 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
CreateLinkedTokenSourceAlways dispose linked token sources immediately with
CODE
using
AsyncMaster · Concurrency Geek
Task Parallel Library (TPL), async/await internals, and lock...
Task Parallel Library (TPL), async/await internals, and lock...
The following users thanked AsyncMaster for this post: