Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# task factory timeout

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 !

like image 485
Rototo Avatar asked May 17 '13 09:05

Rototo


1 Answers

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());
like image 197
Stephen Cleary Avatar answered Oct 27 '22 05:10

Stephen Cleary