Monday, 21 July 2014

Write A Program That Use Multiple Processor In C#

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace time
{
    class Program
    {
        long sum = 0;
        void showTime()
        {
          Thread.Sleep(1000);
        }
        static void Main(string[] args)
        {

            var program = new Program();
           var startTime = DateTime.Now;
           for(int i=0;i<10;i++)
                  {
                    program.showTime();
                  }
            Parallel.For(0, 10, i =>
                {
                    program.sum += i;
                    program.showTime();
                }
                );         
            Console.Write("\n\tTotal Seconda Taken: "+DateTime.Now.Subtract(startTime).TotalSeconds);
            Console.ReadLine();
        }
    }
}

If  We execute this program using the normal for loop only then the program will take at least 10 secs. But by using Parallel.For() we can access multiple processor cores of our computer and in this program multiple processor is getting accessed by the program..

No comments:

Post a Comment