Parallel Programming using Task and Parallel

As we all know that, now a days hardware world is booming and its processing power increases, the responsibility lies with developers to utilize such power. In order to utilize hardware resources more efficiently we should use multi-threading approach in our programming.

In the past, parallelization required low-level manipulation of threads and locks.

Sample for Thread

 //Declare and Start Thread.
 Thread th1 = new Thread(new ThreadStart(SamplePrograme));
 th1.Start();

//Method
public static void SamplePrograme()
{
        Console.WriteLine("Sample Method called using thread.");
}

Visual Studio 2010 and the .NET Framework 4 enhance support for parallel programming by providing a new runtime, new class library types, and new diagnostic tools. These features simplify parallel development so that you can write efficient and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool.

You can start the thread in the same way using Task as shown in below code.

var t3 = new Task(SamplePrograme);
t3.Start();

Task Parallel Library provide various advantages over threading.

>> You can start one task and pass the result of the same to another task and execute it.

var t1 = Task.Factory.StartNew(() => { DoSomeImportantWork("WhiteX"); }).ContinueWith((previousTask) => {DoSomeOtherImportantWork("WhiteX", 1);});

var t2 = Task.Factory.StartNew(() => { DoSomeImportantWork("Mr. X"); }).ContinueWith((previousTask) => { DoSomeOtherImportantWork("Mr. X", 2); });

public static void DoSomeImportantWork(string name) {
            Thread.Sleep(1000);
            Console.WriteLine("Hi, " + name);    
}

public static void DoSomeOtherImportantWork(string name, int i) {
            for (int j = 0; j < 10; j++) {
                counter = j;
                Console.WriteLine("{0} is doing some other important work. Counter value is {1}", name, counter);
            }
}

>> Using Parallel class you can execute the multiple tasks like shown in below code

Parallel.Invoke(() => { DoSomeImportantWork("Mr. A"); }, () => { DoSomeOtherImportantWork("Mr. A", 1); }, () => { DoSomeImportantWork("Mr. B"); }, () => { DoSomeOtherImportantWork("Mr. B", 2); });

>> There are two methods using those you can hold the execution of other codes till specified thread(s) completed. Those methods are:
Task.WaitAll();
Task.WaitAny()

Note*:

What we have  discussed is just the basic to start with Task Parallel Library. You can explore more by defining and executing code with different options.

Complete code for your practice

 

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

namespace TaskParallelLibrary
{
    class Program
    {
        static int counter = 0;
        static void Main(string[] args)
        {
            var t1 = Task.Factory.StartNew(() => { DoSomeImportantWork("WhiteX"); }).ContinueWith((previousTask) => {DoSomeOtherImportantWork("WhiteX", 1);});
            var t2 = Task.Factory.StartNew(() => { DoSomeImportantWork("Mr. X"); }).ContinueWith((previousTask) => { DoSomeOtherImportantWork("Mr. X", 2); });
            
            var t3 = new Task(SamplePrograme);
            t3.Start();
                        
            Task.WaitAll(t1,t2);
            
            Parallel.Invoke(() => { DoSomeImportantWork("Mr. A"); }, () => { DoSomeOtherImportantWork("Mr. A", 1); }, () => { DoSomeImportantWork("Mr. B"); }, () => { DoSomeOtherImportantWork("Mr. B", 2); });

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

            Thread th1 = new Thread(new ThreadStart(SamplePrograme));
            th1.Start();

        }

        public static void SamplePrograme()
        {
            Console.WriteLine("Sample Method called using thread.");
        }

        public static void DoSomeImportantWork(string name) {
            Thread.Sleep(1000);
            Console.WriteLine("Hi, " + name);    
        }

        public static void DoSomeOtherImportantWork(string name, int i) {
            for (int j = 0; j < 10; j++) {
                counter = j;
                Console.WriteLine("{0} is doing some other important work. Counter value is {1}", name, counter);
            }
        }

        
    }
}
Advertisements

One response to “Parallel Programming using Task and Parallel

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