如何为此代码添加超时

Mat*_*ics 6 .net c# task-parallel-library async-await c#-4.0

我试图为此代码添加超时,但因为我是新手,我无法弄清楚,

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

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

编辑

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

Yuv*_*kov 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.
}
Run Code Online (Sandbox Code Playgroud)

您可以使用向.NET 4.0 Microsoft.Bcl.Async添加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.
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑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;
    } 
}
Run Code Online (Sandbox Code Playgroud)