How to add a timeout to this code?

I am trying to add a timeout to this code, but since I am new to this, I cannot figure out

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

I also want the main thread to wait here until 5 minutes expire or end.

Edit

Or can I use a cancellation token with this, if so, how :(?

+6
source share
1 answer

You can create a new Task using Task.Delay and use 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. } 

You can use Microsoft.Bcl.Async to add async-await features to .NET 4.0

Edit:

As you are using VS2010, you can use Task.Factory.ContinueWheAny instead:

 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:

Since Task.Delay not available in .NET 4.0, you can create it yourself using the extension method:

 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; } } 
+6
source

Source: https://habr.com/ru/post/980072/


All Articles