且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何取消正在等待超时而不抛出异常的任务

更新时间:2022-04-17 09:20:29

您可以致电 Task.WaitAny ,其中包含 任务的数组。然后可以对任务的状态执行操作,但方法返回。示例代码:

You could call Task.WaitAny with an array of just that task. Then you can act on the status of the task, however the method returns. Sample code:

using System;
using System.Threading;
using System.Threading.Tasks;

class Test
{
    static void Main()
    {
        Task sleeper = Task.Factory.StartNew(() => Thread.Sleep(100000));

        int index = Task.WaitAny(new[] { sleeper },
                                 TimeSpan.FromSeconds(0.5));
        Console.WriteLine(index); // Prints -1, timeout

        var cts = new CancellationTokenSource();

        // Just a simple wait of getting a cancellable task
        Task cancellable = sleeper.ContinueWith(ignored => {}, cts.Token);

        // It doesn't matter that we cancel before the wait
        cts.Cancel();

        index = Task.WaitAny(new[] { cancellable },
                             TimeSpan.FromSeconds(0.5));
        Console.WriteLine(index); // 0 - task 0  has completed (ish :)
        Console.WriteLine(cancellable.Status); // Cancelled
    }
}

请注意,你应该观察异常,以避免它最终敲定时:)

Note that if the task is faulted, you should "observe" the exception in order to avoid it going bang when it's finalized :)