È possibile creare una nuova Task
utilizzando Task.Delay
e utilizzare 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.
}
È possibile utilizzare Microsoft.Bcl.Async
per aggiungere le capacità di async-await
a .NET 4.0
Edit:
Come stai usando VS2010, si può usare Task.Factory.ContinueWheAny
invece:
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:
Dal Task.Delay
non è disponibile in .NET 4.0, puoi crearlo tu stesso utilizzando un metodo di estensione:
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;
}
}
fonte
2014-12-23 08:09:16
Controlla questo link: http://blogs.msdn.com/b/nikhil_agarwal/archive/2014/04/02/10511934.aspx – danish
Domanda pertinente: http://stackoverflow.com/questions/16605223/c-sharp- task-factory-timeout – supertopi