← Back to C# Course | Chapter 13: Async Programming | Lesson 5 of 6

CancellationToken क्या है

एक CancellationToken किसी लंबे job को पास किया जा सकने वाला एक stop button है, जैसे कोई दोस्त जो 'कृपया रुको' कहने के लिए एक flag लहरा सके। job इसे जांचता है और शालीनता से खत्म हो जाता है।

In this page:

  1. CancellationToken
Syntax
csharp
using var cts = new CancellationTokenSource();
cts.CancelAfter(milliseconds);   // or cts.Cancel();

await Task.Delay(milliseconds, cts.Token);   // throws OperationCanceledException

CancellationToken

CancellationToken किसी चल रहे asynchronous operation को जल्दी रुकने का signal देने का एक cooperative तरीका प्रदान करता है।

एक CancellationTokenSource token बनाता है और .Cancel() से cancellation trigger कर सकता है; चल रहा code token.IsCancellationRequested जांचता है या किसी awaited method को OperationCanceledException फेंकने देता है। Cancellation cooperative है — operation को असल में रुकने के लिए token को सक्रिय रूप से जांचना चाहिए।

Note: वही CancellationToken हर awaited call में नीचे पास करें ताकि cancellation सही से propagate हो।

उदाहरण: CancellationToken

markup
using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using var cts = new CancellationTokenSource();
        cts.CancelAfter(50);

        try
        {
            await Task.Delay(1000, cts.Token);
            Console.WriteLine("Completed normally");
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("Operation was cancelled");
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. token को कभी inner calls को पास न करना, जिससे cancellation का कोई असर नहीं होता।
  2. लंबे loops में IsCancellationRequested न जांचना।
  3. OperationCanceledException catch करना भूल जाना।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.