如何为此代码添加超时

时间:2014-12-23 08:06:44

标签: c# .net c#-4.0 task-parallel-library async-await

我正在尝试为此代码添加超时,但因为我是新手,我无法弄明白,

Task.Factory.StartNew(() =>
{
     Aspose.Words.Document doc = new Aspose.Words.Document(inputFileName);
     doc.Save(Path.ChangeExtension(inputFileName, ".pdf"));
});

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

修改

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

1 个答案:

答案 0 :(得分:6)

您可以使用Task创建新的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:

由于.NET 4.0中没有Task.Delay,因此您可以使用扩展方法自行创建:

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;
    } 
}