Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add timeout to this code [duplicate]

I am trying to add timeout to this code, but because I am new to this, I can't figure out,

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

Also I want main thread to wait here until it timeout for 5 minutes or completes.

Edit

Or can I use cancellation token with this, if yes then how :( ?

like image 752
Mathematics Avatar asked Dec 23 '14 08:12

Mathematics


1 Answers

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 abilities to .NET 4.0

Edit:

As you're 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 isn't available in .NET 4.0, you can create it yourself using an 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;
    } 
}
like image 158
Yuval Itzchakov Avatar answered Oct 14 '22 00:10

Yuval Itzchakov