加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在没有抛出异常的情况下取消等待超时的任务

发布时间:2020-12-15 18:18:02 所属栏目:百科 来源:网络整理
导读:使用取消令牌取消具有超时(在超时结束之前)的任务时,将引发异常.例: mytask.start();bool didTaskRunInTime = mytask.wait(5 mins,_cancelToken); 这意味着我不能继续下面. //was the task cancelledif (_cancelToken.IsCancelRequested){ // log cancel fr
使用取消令牌取消具有超时(在超时结束之前)的任务时,将引发异常.例:
mytask.start();
bool didTaskRunInTime = mytask.wait(5 mins,_cancelToken);

这意味着我不能继续下面.

//was the task cancelled
if (_cancelToken.IsCancelRequested)
{
    // log cancel from user to file etc
}

if (didTaskRunInTime )
{
    int taskResult = myTask.Result;
    // log result to file
}
else if (!_cancelToken.IsCancelRequested)
{
    // Tell user task timed out,log a message etc
}

我将不得不在我的catch块中完成所有这些操作并且我的代码看起来很混乱.这样做的正确方法是什么?

解决方法

您可以使用该任务的数组调用 Task.WaitAny.然后,您可以对任务的状态进行操作,但方法会返回.示例代码:
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
    }
}

请注意,如果任务出现故障,您应该“观察”异常,以避免在最终确定时发生爆炸:)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读