Last active
February 17, 2021 17:25
-
-
Save pizycki/4c052e979dd277fc0861c0c30d5454d9 to your computer and use it in GitHub Desktop.
Timeout operation with .NET CancellationTokenSource
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async Task Main() | |
{ | |
var sw = new Stopwatch(); | |
sw.Start(); | |
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)); | |
await Foo(cts.Token); | |
sw.Stop(); | |
Console.WriteLine("Elapsed " + sw.ElapsedMilliseconds); | |
} | |
async Task Foo(CancellationToken ct) | |
{ | |
while (true) | |
{ | |
if (ct.IsCancellationRequested) | |
{ | |
return; | |
} | |
await Task.Delay(200); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment