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

c# – 如何为此代码添加超时

发布时间:2020-12-15 08:46:07 所属栏目:百科 来源:网络整理
导读:参见英文答案 Asynchronously wait for TaskT to complete with timeout12个 我试图为此代码添加超时,但因为我是新手,我无法弄清楚, Task.Factory.StartNew(() ={ Aspose.Words.Document doc = new Aspose.Words.Document(inputFileName); doc.Save(Path.Cha
参见英文答案 > Asynchronously wait for Task<T> to complete with timeout12个
我试图为此代码添加超时,但因为我是新手,我无法弄清楚,
Task.Factory.StartNew(() =>
{
     Aspose.Words.Document doc = new Aspose.Words.Document(inputFileName);
     doc.Save(Path.ChangeExtension(inputFileName,".pdf"));
});

此外,我希望主线程在此等待,直到它超时5分钟或完成.

编辑

或者我可以使用取消令牌,如果是,那么如何:(?

解决方法

您可以使用Task.Delay创建一个新任务并使用Task.WhenAny:
Task delayedTask = Task.Delay(TimeSpan.FromMinutes(5));
Task workerTask = Task.Factory.StartNew(() =>
{
     Aspose.Words.Document doc = new Aspose.Words.Document(inputFileName);
     doc.Save(Path.ChangeExtension(inputFileName,".pdf"));
});

if (await Task.WhenAny(delayedTask,workerTask) == delayedTask)
{
   // We got here because the delay task finished before the workertask.
}
else
{
   // We got here because the worker task finished before the delay.
}

您可以使用Microsoft.Bcl.Async向.NET 4.0添加async-await功能

编辑:

当您使用VS2010时,您可以使用Task.Factory.ContinueWheAny:

Task.Factory.ContinueWhenAny(new[] { delayedTask,workerTask },task =>
{
    if (task == delayedTask)
    {
        // We got here if the delay task finished before the workertask.
    }
    else
    {
        // We got here if the worker task finished before the delay.
    }
});

编辑2:

由于Task.Delay在.NET 4.0中不可用,您可以使用扩展方法自己创建它:

public static class TaskExtensions
{
    public static Task Delay(this Task task,TimeSpan timeSpan)
    {
        var tcs = new TaskCompletionSource<bool>();
        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Elapsed += (obj,args) =>
        {
            tcs.TrySetResult(true);
        };
        timer.Interval = timeSpan.Milliseconds;
        timer.AutoReset = false;
        timer.Start();
        return tcs.Task;
    } 
}

(编辑:李大同)

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

    推荐文章
      热点阅读