C# task factory timeout

Rototo picture Rototo · May 17, 2013 · Viewed 21.4k times · Source

I have to execute a long process operation in a thread and continue by returning the result to a function. Here is my code :

Task<ProductEventArgs>.Factory.StartNew(() =>
    {
        try
        {
             // long operation which return new ProductEventArgs with a list of product

        }
        catch (Exception e)
        {
            return new ProductEventArgs() { E = e };
        }

    }).ContinueWith((x) => handleResult(x.Result), TaskScheduler.FromCurrentSynchronizationContext());

The problem is actually I don't have a timeout. I want to put a timer in order to return something like this :

   new ProductEventArgs() { E = new Exception("timeout") }; 

if the timeout is reached. Can't use await/async. Thanks a lot !

Answer

Stephen Cleary picture Stephen Cleary · May 17, 2013

You should use CancellationTokens:

var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var token = cts.Token;
Task<ProductEventArgs>.Factory.StartNew(() =>
{
    try
    {
        // occasionally, execute this line:
        token.ThrowIfCancellationRequested();
    }
    catch (OperationCanceledException)
    {
        return new ProductEventArgs() { E = new Exception("timeout") };
    }
    catch (Exception e)
    {
        return new ProductEventArgs() { E = e };
    }

}).ContinueWith((x) => handleResult(x.Result), TaskScheduler.FromCurrentSynchronizationContext());