Basic Parallel Programming

 19-Apr-2014   nityaprakash     TPL  ChildTask  ChildTask    Comments  0

Parallel programming is now become a basic or can be said essential now days. Everywhere it is being used. It is time to Learn it properly and start using for faster task execution. Computers now more powerful and occupied with multi-core processor to handle multiple complex tasks. I haven't got chance to use extensively in my applications. I am can be said new to it. My first article was Multi-threading using TPL was just introduction.

Creating The Task

Lets take a example below which demos, how can we create task with parameter and without parameter. Task can be return a specific type of object which already being described in Task<TResult> section of Multi-threading using TPL.


       static void Main(string[] args)
        {
            //Task with lamba expression and without parameter and anonymous method.
            Task task1 = new Task(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine("Task One: {0}", i);
                    Thread.Sleep(100);
                }
            });

            //Concrete method and state
            Task task2 = new Task((obj) => PrintMessage(obj), "Two");

            task1.Start();
            task2.Start();

            Console.WriteLine("Main method is completed.  Please enter to finish.");
            Console.ReadLine();
        }

        static void PrintMessage(object obj)
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Task {0}:{1}", obj, i);
                Thread.Sleep(100);
            }

        }

task1 is created using lambda expression assuming there is no parameter required but we can pass n number of parameters in the approach. task2 is another approach where we are calling PrintMessag(obj) function using Lambda expression which is equal to below statement:


    Action<object> p = new Action<object>(PrintMessage);
    Task task2 = new Task(p, "Two");

Action object can be created of only which take one parameter of type object.

Waiting For the Task

If Task2 is depend on output of Task1, we should call task1.Wait() method before starting task2.

Attaching Child Task

There may be scenario tasks inside a running task can be run parallel but those are part of parent task. Main task cannot be considered completed until all child task complete executing. In this case all child class must be attached to parent class in order to make a logic unit of work:


        static void Main(string[] args)
        {

            Task task1 = new Task((obj) => PrintMessage(obj), "One");

            Task task2 = new Task((obj) => PrintMessage(obj), "Two");

            task1.Start();
            task2.Start();

            Console.WriteLine("Main method is completed.  Please enter to finish.");
            task1.Wait();
            task2.Wait();
            //Console.ReadLine();
        }

        static void PrintMessage(object obj)
        {
            for (int i = 0; i < 10; i++)
            {
                int abc = i;
                Task.Factory.StartNew(() =>
                {
                    for (int j = 0; j < 5; j++)
                    {
                        Thread.Sleep(1000);
                        Console.WriteLine("{0}:child:{1}", obj, abc);
                    }
                }, TaskCreationOptions.AttachedToParent);

                Console.WriteLine("Task {0}:{1}", obj, i);
                Thread.Sleep(100);
            }

        }

Wrap Up

This post is just simply creating a task with parameter to improve the efficiency of user program and utilizing the available resources in optimized manner.


Nitya Prakash Sharma has over 10 years of experience in .NET technology. He is currently working as Senior Consultant in industry. He is always keen to learn new things in Technology and eager to apply wherever is possible. He is also has interest in Photography, sketching and painting.

My Blog
Post Comment

COMMENTS