Вы можете создать новый 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
, чтобы добавить async-await
к .NET 4.0
Edit:
Как вы используете 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.
}
});
Edit 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;
}
}
Проверьте эту ссылку: http://blogs.msdn.com/b/nikhil_agarwal/archive/2014/04/02/10511934.aspx – danish
Соответствующий вопрос: http://stackoverflow.com/questions/16605223/c-sharp- task-factory-timeout – supertopi