Home > Development > Task Continuations 1

Task Continuations 1


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace TPLSamples
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Program p = new Program();
            p.TestingTaskContinuations();

            Console.WriteLine("Press any key to quit...");
            Console.ReadKey();
        }

        public void TestingTaskContinuations()
        {

            CancellationTokenSource source = new CancellationTokenSource();
            var token = source.Token;

            Task<int> t1 = Task.Factory.StartNew(() => 42, token);

            Task t2 = t1.ContinueWith(x =>
            {
                Thread.Sleep(400);
                token.ThrowIfCancellationRequested();
                Console.WriteLine(x.Result);
            }, token);

            Task t3 = t1.ContinueWith(x =>
            {
                Thread.Sleep(400);
                token.ThrowIfCancellationRequested();
                Console.WriteLine(x.Result);
            }, token);

            Task t4 = t1.ContinueWith(x =>
            {
                Thread.Sleep(400);
                token.ThrowIfCancellationRequested();
                Console.WriteLine(x.Result);
            }, token);

            Task t5 = t1.ContinueWith(x =>
            {
                throw new Exception("Random Exception...."); // Not propogated up the chain as no parent / child setup
            }, token);

           
            Thread.Sleep(100);
            Console.WriteLine("Status: {0}", t1.Status.ToString());

            source.Cancel();
        }
    }
}
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: