检查CancellationToken是否已取消

编程入门 行业动态 更新时间:2024-10-26 08:28:14
本文介绍了检查CancellationToken是否已取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我创建了一个演示项目,以帮助我了解如何使用取消令牌.我了解您已取消令牌并检查是否已请求取消,但是有什么方法可以检查是否已实现取消?在下面的示例中,我不想在DoWork()完成运行之前再次运行Work().

I've created a little demo project to help me understand how I can use Cancellation Tokens. I understand that you cancel a token and check if a cancellation has been requested, but is there a way that I can check whether the cancellation has been realised? In my example below, I don't want to run Work() again until DoWork() has finished running.

public class Program { public static CancellationTokenSource tokenSource; private static void Main(string[] args) { while (true) { Work(); } } public static async void Work() { tokenSource = new CancellationTokenSource(); Console.WriteLine("Press any key to START doing work"); Console.ReadLine(); Console.WriteLine("Press any key to STOP doing work"); DoWork(tokenSource.Token); Console.ReadLine(); Console.WriteLine("Stopping..."); tokenSource.Cancel(); } public static async void DoWork(CancellationToken cancelToken) { while (true) { Console.WriteLine("Working..."); await Task.Run(() => { Thread.Sleep(1500); }); if (cancelToken.IsCancellationRequested) { Console.WriteLine("Work Cancelled!"); return; } } } }

推荐答案

如果您的所有操作都是异步的并且可以取消的,那么您将可以充分利用 CancellationToken 的优势.这种取消令牌的方法将立即生效.您不必等待 Thread.Sleep 或其他阻止调用完成.

You will make the most out of a CancellationToken if all your operations are asynchronous and cancellable. This way cancelling the token will have immediate effect. You won't have to wait for a Thread.Sleep or other blocking call to complete.

public static async Task DoWork(CancellationToken cancellationToken) { while (true) { await Console.Out.WriteLineAsync("Working..."); await Task.Delay(1500, cancellationToken); } }

在此示例中,令牌仅传递给 Task.Delay ,因为 WriteLineAsync 在.NET Framework上(在.NET Core上)无法取消.

In this example the token is passed only to Task.Delay, because the WriteLineAsync is not cancellable on .NET Framework (it is on .NET Core).

取消令牌时, Task.Delay 将引发 OperationCanceledException .

更多推荐

检查CancellationToken是否已取消

本文发布于:2023-11-12 21:41:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582601.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:CancellationToken

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!