本文介绍了取消令牌的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在尝试学习如何使用取消令牌取消任务。 在这里,我已经为此编写了一个UnitTest,但是我没有得到它的工作方式。I am trying learn how to cancel Task using cancellation token.Here, I have written a UnitTest for it but I am not getting the way it is working.[TestMethod]public async Task Task_should_not_run_when_token_cancelled_before_its_call(){ var cts = new CancellationTokenSource(); var token = cts.Token; cts.Cancel(); Debug.WriteLine("Calling Cancellable Method".ToUpper()); try { await CheckMeCalled(token); } catch (Exception expException) { }}private async Task CheckMeCalled(CancellationToken ct){ Debug.WriteLine("Before task delayed".ToUpper()); await Task.Delay(5000); Debug.WriteLine("After task delayed".ToUpper());}在上述测试中,我称为 cts。在调用 CheckMeCalled 方法之前,先取消()。因此它不应在取消后运行。 In the above test, I called the cts.Cancel() before calling the CheckMeCalled method. so it should not run as it canceled. But it is running to the full extent.我在某处读到:但是,这似乎没有发生。有人会向我解释吗?But it is not seems to be happening here. Would somebody explain it to me?推荐答案您添加的报价与创建新的 Task 通过 Task.Run 或 Task.Factory.Startnew 。将 CancellationToken 传递给您的方法时,必须在运行前主动检查令牌The quote you added was related to creating a new Task via Task.Run or Task.Factory.Startnew. When passing a CancellationToken to your method, you have to actively check the token before runningprivate async Task CheckMeCalled(CancellationToken ct){ ct.ThrowIfCancellationRequested(); Debug.WriteLine("Before task delayed".ToUpper()); await Task.Delay(5000, ct); Debug.WriteLine("After task delayed".ToUpper());}以下是斯蒂芬·图布(Stephan Toub)关于取消令牌和任务:Here is a quote by Stephan Toub regarding cancellation token and Task:我还建议阅读 NET 4取消框架进行了广泛的回顾PFX小组的取消机制I also recommend reading NET 4 Cancellation Framework for a broad review of the cancellation mechanism by the PFX Team 这篇关于取消令牌的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-30 01:51