csharp

异步编程(五):async/await模式之取消执行

2019-02-24  本文已影响0人  曦航老袁

在async/await模式下,一些.NET的异步方法是允许取消执行的。System.Theading.Tasks命名空间(更正:此处应该是System.Theading命名空间)中有两个类是为此目的而设计的:CancellationToken和CancellationTokenSource。

class Program
{
    static void Main()
    {
        CancellationTokenSource cts = new CancellationTokenSource();
        CancellationToken token = new CancellationToken();

        MyClass mc = new MyClass();
        Task t = mc.RunAsync(token);

        Thread.Sleep(3000);
        cts.Cancel();

        t.Wait();
        Console.WriteLine("Was Cancellationed: {0}",token.IsCancellationRequested);
    }
 }

class MyClass
{
    public async Task RunAsync(CancellationToken ct)
    {
        if (ct.IsCancellationRequested) return;
        await Task.Run(() => CycleMethod(ct), ct);
    }

    void CycleMethod(CancellationToken ct)
    {
        Console.WriteLine("Starting CycleMethod");
        const int max = 5;
        for (int i = 0; i < max; i++)
        {
            if (ct.IsCancellationRequested) return;         // 监控CancellationToken
            Thread.Sleep(1000);
            Console.WriteLine("     {0} of {1} iterations completed", i + 1, max);
        }
    }
}

代码中循环设置为5次,但3秒后被取消,产生的结果如下:

Starting CycleMethod
     1 of 5 iterations completed
     2 of 5 iterations completed
     3 of 5 iterations completed
Was Cancellationed: True
上一篇下一篇

猜你喜欢

热点阅读