使异步代码可取消 [英] Making asynchronous code cancellable

查看:59
本文介绍了使异步代码可取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些耗时的方法:

public class TimeConsumingClass
{
   public void TimeConsumingMethod()
   {
      //let's imagine my method works this way
      for (var i = 0; i < 10000; i++)
         Thread.Sleep();
   }
}

它先前在主线程中执行过.然后我需要在辅助线程中调用它以不阻止UI:

It was executed in main thread previously. Then I needed to call it in secondary thread to not block UI:

Task.Factory.StartNew(() => { new TimeConsumingClass().TimeConsumingMethod(); });

现在,我需要使随时可以停止此方法成为可能.所以我想让我的方法以某种方式对待CancellationToken,同时我想保持同步调用此方法的可能性(没有CancellationToken).我想到的最好的主意是在我的方法中添加可选的CancellationToken参数,默认情况下该参数为null(对于同步调用):

And now I need to make it possible to stop this method at any time. So I want to make my method treat CancellationToken somehow and at the same time I want to keep possibility to call this method synchronously (without CancellationToken). The best idea I came to is to add optional CancellationToken argument to my method which will be null by default (for synchronous calls):

public class TimeConsumingClass
{
   public void TimeConsumingMethod(CancellationToken cancellationToken = null)
   {
      //let's imagine my method works this way
      for (var i = 0; i < 10000; i++)
      {
         if (cancellationToken.IsCancellationRequested)
           return;
         Thread.Sleep();
      }
   }
}

但是,.NET多线程最近有很多创新,我觉得这是一种更好的方式来完成我将要做的事情.有一个吗?

But there was a lot of innovation in .NET multithreading recently and I have a feeling the is a better way to do what I am going to do. Is there one?

推荐答案

如果您正在寻找一种更现代"的方法,最好的方法是研究新的 async 并c#中的 await 关键字.到目前为止,它们是实现异步性的最直接方法.

If you're looking for a more "modern" way to do it, your best bet is to study the new async and await keywords in c#. They are by far the most straightforward way to implement asynchronicity.

您可以在这里找到 async await 的很好的介绍:

You can find a good introduction to async and await here:

使用Async和Await(C#和Visual Basic)进行异步编程
http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

要了解如何报告进度和取消异步方法,请阅读此处:

To find out how to report progress and cancel asynchronous methods, read here:

4.5中的异步:在异步API中启用进度和取消
要取消使用与您在问题中使用的代码相同的样式的任务,请查看此处:

To cancel tasks in the same style of the code you're using in your question, look here:

任务取消
http://msdn.microsoft.com/en-us/library/dd997396.aspx

这篇关于使异步代码可取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆