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

前端之家收集整理的这篇文章主要介绍了c# – 如何为此代码添加超时前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > 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;
    } 
}
原文链接:https://www.f2er.com/csharp/244793.html

猜你在找的C#相关文章