A day with .Net

My day to day experince in .net

Archive for the ‘Parallel Programming’ Category

Monitor Task Cancellation With Delegate

Posted by vivekcek on August 21, 2012

After we cancel a task. The delegate registered with the token will be executed

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TaskCancelDelegate
{
    class Program
    {
        static CancellationTokenSource tokenSource = new CancellationTokenSource();
        static CancellationToken token = tokenSource.Token;
        static void Main(string[] args)
        {
            Task t1 = new Task(() => Iterate(), token);
            //Delegate reistartion with token
            token.Register(() => { Console.WriteLine("Task Cancellation called Message from delegate"); });
            Console.WriteLine("Task Started");
            t1.Start();
            System.Threading.Thread.Sleep(2000);
            Console.WriteLine("Task Cancelling call");
            tokenSource.Cancel();
            try
            {
                t1.Wait();
            }
            catch (AggregateException ag)
            {
                Console.WriteLine(ag.InnerException.Message.ToString());
            }

            Console.ReadLine();
        }
        static void Iterate()
        {
            for (int i = 0; i < int.MaxValue; i++)
            {
                if (token.IsCancellationRequested)
                {
                    throw new OperationCanceledException("Task Cancelled Exception");
                }
                else
                {
                    Console.WriteLine(i.ToString());
                }
            }
        }
    }
}

Posted in Parallel Programming | Leave a Comment »

Cancelling Tasks

Posted by vivekcek on August 19, 2012

I hope you have some experience with Thread Pool in .net. We can queue work items to thread pool and wait for all to complete. But it was very hard to control the queued work items. So here comes TPL. We can cancel a task when it is working. Try out this code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TaskCancel
{
    class Program
    {
        static CancellationTokenSource tokenSource ;
        static CancellationToken token;
        static void Main(string[] args)
        {

            tokenSource = new CancellationTokenSource();
            token = tokenSource.Token;
            Task t1 = new Task(() => iterate(),token);
            t1.Start();
            System.Threading.Thread.Sleep(100);
            tokenSource.Cancel();
            Console.ReadLine();
        }

        static void iterate()
        {
           
                for (int i = 0; i < int.MaxValue; i++)
                {
                    if (token.IsCancellationRequested)
                    {
                        throw new OperationCanceledException();
                    }
                    else
                    {
                        Console.WriteLine(i);
                    }
                }
            
        }
        
    }
}

Posted in Parallel Programming | Leave a Comment »

Exception Handling with the Task Parallel Library

Posted by vivekcek on August 19, 2012

We use the AggregateException class to handle exception in task’s

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExceptionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Task<int> t1 = new Task<int>(() => Add());
            try
            {
                t1.Start();
                t1.Wait();
            }
            catch (AggregateException ag)
            {
                Console.WriteLine(ag.InnerExceptions[0].Message);
            }
            Console.ReadLine();
        }
        static int Add()
        {
            
                
            throw new ArgumentException("Exception");
            
           
        }
    }
}

Posted in Parallel Programming | Leave a Comment »

Passing arguments to a task

Posted by vivekcek on August 19, 2012

Look at the example below. Hope it is simple to understand.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetResult1
{
    class Program
    {
        static void Main(string[] args)
        {
            Task<int> t1 = new Task<int>(() => Add(1,2));
            t1.Start();
            Console.WriteLine("Result: {0}", t1.Result);
            Console.ReadLine();
        }
        static int Add(int a,int b)
        {
            return a + b;
        }
    }
}

Posted in Parallel Programming | Leave a Comment »

Getting result from A task

Posted by vivekcek on August 19, 2012

Some times your task may return some value. In this post i will show how to get an integer result from a task you created.

For that you have to use the generic version of task Task.

The Result property of Task will give result of type T.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetResult1
{
    class Program
    {
        static void Main(string[] args)
        {
            Task<int> t1 = new Task<int>(() => Add());
            t1.Start();
            Console.WriteLine("Result: {0}", t1.Result);
            Console.ReadLine();
        }
        static int Add()
        {
            return 1 + 2;
        }
    }
}


Posted in Parallel Programming | Leave a Comment »

Creating and starting task

Posted by vivekcek on August 19, 2012


In this post i mentioned the various method to create and start a task
.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartTask
{
    class Program
    {
        static void Main(string[] args)
        {
            //Using Action
            Task t1 = new Task(new Action(SayHello));
            t1.Start();

            //Using delegate
            Task t2 = new Task(delegate { SayHello(); });
            t2.Start();

            //Lambda Expression
            Task t3 = new Task(() => SayHello());
            t3.Start();

            //Anonymous Metod
            Task t4 = new Task(() => { Console.WriteLine("Hello"); });
            t4.Start();


            ////////Task.Factory/////////////

            //No need to call any start method
            Task.Factory.StartNew(() => SayHello());

            Console.ReadLine();
        }
        static void SayHello()
        {
            Console.WriteLine("Hello");
        }
    }
}

Posted in Parallel Programming | Leave a Comment »