Tasks with Timeouts – Contd.

As mentioned in the last post we can now have tasks with individual timeouts. The code looked a little heavy. Can we do better ? Yes we can !!


var tasks = new List<Task>();
try
{
//instead of checking for fault within the continutaion, 
//we can just use a TaskContinuationOption to tell communicate the right semantics

var t1 = Task.Factory.StartNew(_ => LongRunningTask(), TaskCreationOptions.AttachedToParent)
              .TimeoutAfter(1000)
              .ContinueWith(t => SomethingUsefulWithTheResult(), 
                                 TaskContinuationOptions.NotOnFaulted);

var t2 = Task.Factory.StartNew(_ => LongRunningTask(), TaskCreationOptions.AttachedToParent)
              .ContinueWith(t => SomethingUsefulWithTheResult());

var t3 = Task.Factory.StartNew(_ => LongRunningTask("Entering task3"), TaskCreationOptions.AttachedToParent)
              .ContinueWith(t => SomethingUsefulWithTheResult());
            
tasks.Add(t1);
tasks.Add(t2);
tasks.Add(t3);
                            
Task.WaitAll(tasks.ToArray());
}
catch (Exception ex)
{                
    Console.WriteLine("There was an exception");
    Console.WriteLine(ex.InnerException.Message);               
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s