CancellationToken क्या है
एक CancellationToken किसी लंबे job को पास किया जा सकने वाला एक stop button है, जैसे कोई दोस्त जो 'कृपया रुको' कहने के लिए एक flag लहरा सके। job इसे जांचता है और शालीनता से खत्म हो जाता है।
In this page:
Syntax
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
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");
}
}
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- token को कभी inner calls को पास न करना, जिससे cancellation का कोई असर नहीं होता।
- लंबे loops में
IsCancellationRequestedन जांचना। OperationCanceledExceptioncatch करना भूल जाना।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: