Making asynchronous code cancellable

青春壹個敷衍的年華 提交于 2021-02-07 20:33:22

问题


I have some time-consuming method:

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

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(); });

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();
      }
   }
}

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?


回答1:


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.

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

Asynchronous Programming with Async and Await (C# and 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:

Async in 4.5: Enabling Progress and Cancellation in Async APIs
http://blogs.msdn.com/b/dotnet/archive/2012/06/06/async-in-4-5-enabling-progress-and-cancellation-in-async-apis.aspx

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

Task Cancellation
http://msdn.microsoft.com/en-us/library/dd997396.aspx



来源:https://stackoverflow.com/questions/15438937/making-asynchronous-code-cancellable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!