C# Mastery

CancellationToken Mastery: Surgically Aborting Operations

1 Views Updated 5/4/2026

Mastering CancellationTokens

In a high-pressure Web API, users often cancel requests (by closing the browser tab or hitting refresh). If your server continues to process a 30-second report for a user who is no longer there, you are wasting CPU and DB resources. CancellationTokens allow you to stop "Ghost Requests" instantly.

1. How it works: The Cooperative Pattern

Cancellation in .NET is Cooperative. You cannot "violently" kill a thread from the outside (that's dangerous). Instead, you pass a token to the method, and the method periodically checks: "Has someone asked me to stop?"

public async Task ProcessData(CancellationToken ct) 
{
    foreach(var item in items) 
    {
        // Check if the user cancelled
        ct.ThrowIfCancellationRequested();
        
        await DoWork(item, ct); // Pass the token deep into the next method!
    }
}

2. Setting a Time-Out

You can create a token that automatically "fires" after a certain number of seconds, providing a clean way to implement timeouts without complex timer logic.

var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try 
{
    await LongMethod(cts.Token);
}
catch (OperationCanceledException) 
{
    Console.WriteLine("Task took too long and was aborted!");
}

4. Interview Mastery

Q: "Why should I pass a CancellationToken all the way down to EF Core or HttpClient methods?"

Architect Answer: "To prevent Resource Leaks. If you fire a massive SQL query but the user cancels the HTTP request, and you DON'T pass the token to EF Core, the SQL Server will continue working for minutes, wasting memory and potentially locking tables for a result that will literally be thrown in the trash when it returns to C#. By passing the token, EF Core actually sends a 'Cancel' signal to the SQL Server, killing the remote process immediately. It is the single most effective way to improve the 'Stability' of a high-traffic system."

C# Mastery
1. Modern C# & Framework Fundamentals
Introduction to the .NET Ecosystem & Runtime (JIT, CLR) C# 12/13 Top-Level Statements & Global Usings Variables, Data Types, and Value vs Reference Deep Dive Mastering Nullable Reference Types & Null Safety The Magic of Strings (Interpolation, Verbatim, and Immutability)
2. Control Flow & Logical Structures
Advanced Pattern Matching (Switch Expressions) The Precision of Numbers: Checked vs Unchecked Math Iterators: Foreach, Yield Return, and Deferred Execution Defensive Programming: Guard Clauses and Exception Mastery
3. Object-Oriented Mastery
Classes vs Structs vs Records (Which to use when?) Mastering Primary Constructors & Object Initializers Interface Architectures: Default Implementations & Segregation Polymorphism vs Composition (The Architect's Dilemma) Partial Classes, Extension Methods, and Static Classes
4. Functional C# & Collections
Delegates, Func, Action, and Predicates Lambda Expressions & The Evolution of Linq Dynamic Array Management: List<T>, Dictionary, and HashSet Custom Collections & Yielding Data streams
5. Asynchronous & Parallel Programming
Async/Await Deep Dive: Task Lifecycle & Thread Safety Synchronization Context & Avoiding Deadlocks Parallel.ForEach vs PLINQ vs Tasks CancellationToken Mastery: Surgically Aborting Operations
6. Advanced Engineering & High Performance
Generics & Constraints: Building Type-Safe Libraries Reflection and Attributes: Reading Metadata at Runtime Dependency Injection Internals (ServiceCollection from scratch) High-Performance Memory: Span<T> and ReadOnlySpan<T> Garbage Collection Segments & LOH Internals Managing Unmanaged Resources: IDisposable & Finalizers Introduction to Source Generators & Interceptors C# Interview Masterclass: Architect-Level Explanations