Skip to content

Instantly share code, notes, and snippets.

@pizycki
Last active February 17, 2021 17:25
Show Gist options
  • Save pizycki/4c052e979dd277fc0861c0c30d5454d9 to your computer and use it in GitHub Desktop.
Save pizycki/4c052e979dd277fc0861c0c30d5454d9 to your computer and use it in GitHub Desktop.
Timeout operation with .NET CancellationTokenSource
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