Click here to Skip to main content
15,885,920 members
Articles / Programming Languages / C#

Multi Core Programming using Task Parallel Library with .NET 4.0

Rate me:
Please Sign up or sign in to vote.
4.76/5 (96 votes)
9 Apr 2012CPOL6 min read 301.3K   12.9K   207  
The task parallel library allows you to write code which is human readable, less error prone, and adjusts itself with the number of Cores available.
  • ConsoleApplication1.zip
    • ConsoleApplication1
      • ConsoleApplication1
        • _ReSharper.ConsoleApplication1
          • BuildScriptCache
            • .crc
            • .version
            • 3
              • 6d216f12.dat
          • DecompilerCache
          • ModuleIds.xml
          • NamedArguments
            • .crc
            • .version
            • 1
              • 60d8746c.dat
          • PdbInfo
          • ProjectModel
            • ProjectModel.dat
          • Resources
            • .crc
            • .version
          • SymbolCache.bin
          • TagPrefixes
            • .crc
            • .version
          • TodoCache
            • .crc
            • .version
            • 6
              • 460d4b47.dat
          • WebsiteFileReferences
            • .crc
            • .version
          • WordIndex
            • .crc
            • .version
            • 1
              • 60d8746c.dat
        • ConsoleApplication1.5.1.ReSharper.user
        • ConsoleApplication1.sln
        • ConsoleApplication1.suo
        • ConsoleApplication1
  • MatrixMultiplication.zip
    • MatrixMultiplication
      • _ReSharper.MatrixMultiplication
        • BuildScriptCache
          • .crc
          • .version
          • 7
            • 729fb83f.dat
        • DecompilerCache
        • ModuleIds.xml
        • NamedArguments
          • .crc
          • .version
          • 5
            • 6656bd99.dat
        • PdbInfo
        • ProjectModel
          • ProjectModel.dat
        • Resources
          • .crc
          • .version
        • SymbolCache.bin
        • TagPrefixes
          • .crc
          • .version
        • TodoCache
          • .crc
          • .version
          • 7
            • 729fb83f.dat
        • WebsiteFileReferences
          • .crc
          • .version
        • WordIndex
          • .crc
          • .version
          • 5
            • 6656bd99.dat
      • MatrixMultiplication.5.1.ReSharper.user
      • MatrixMultiplication.sln
      • MatrixMultiplication.suo
      • MatrixMultiplication
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main()
        {
            var watch = new Stopwatch();

            const int maxWaitHandleWaitAllAllowed = 64;
            var mres = new ManualResetEventSlim[maxWaitHandleWaitAllAllowed];

            for (var i = 0; i < mres.Length; i++)
            {
                mres[i] = new ManualResetEventSlim(false);
            }


            watch.Start();

            //start a new classic Thread and signal the ManualResetEvent when its done
            //so that we can snapshot time taken, and 

            for (var i = 0; i < mres.Length; i++)
            {
                var idx = i;
                var t = new Thread(state =>
                                       {
                                           for (var j = 0; j < 10; j++)
                                           {
                                               Console.WriteLine(string.Format("Thread : {0}, outputing {1}",
                                                                               state.ToString(), j.ToString()));
                                           }
                                           mres[idx].Set();
                                       });
                t.Start(string.Format("Thread{0}", i));
            }

            WaitHandle.WaitAll((from x in mres select x.WaitHandle).ToArray());

            var threadTime = watch.ElapsedMilliseconds;
            watch.Reset();

            foreach (ManualResetEventSlim t in mres)
            {
                t.Reset();
            }

            watch.Start();

            for (var i = 0; i < mres.Length; i++)
            {
                var idx = i;
                Task.Factory.StartNew(state =>
                                                      {
                                                          for (var j = 0; j < 10; j++)
                                                          {
                                                              Console.WriteLine(
                                                                  string.Format("Task : {0}, outputing {1}",
                                                                                state.ToString(), j.ToString()));
                                                          }
                                                          mres[idx].Set();
                                                      }, string.Format("Task{0}", i));
            }

            WaitHandle.WaitAll((from x in mres select x.WaitHandle).ToArray());
            var taskTime = watch.ElapsedMilliseconds;

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Traditional Thread Approach   : {0}ms", threadTime);
            Console.WriteLine("Task Parallel Library Approach: {0}ms", taskTime);
            Console.ForegroundColor = ConsoleColor.White;

            foreach (var t in mres)
            {
                t.Reset();
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions