Można utworzyć nowy Task
użyciu Task.Delay
i używać 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.
}
Możesz użyć Microsoft.Bcl.Async
, aby dodać zdolności async-await
do .NET 4.0
Edit:
Jak używasz VS2010, można użyć Task.Factory.ContinueWheAny
zamiast:
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.
}
});
Edit 2:
Task.Delay
Ponieważ nie jest dostępne w .NET 4.0, możesz go utworzyć samodzielnie przy użyciu metody rozszerzającej:
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;
}
}
Sprawdź ten link: http://blogs.msdn.com/b/nikhil_agarwal/archive/2014/04/02/10511934.aspx – danish
Istotne pytanie: http://stackoverflow.com/questions/16605223/c-sharp- task-factory-timeout – supertopi