Wednesday, October 21, 2015

How to use Parallel Loops in C# how it improves performance??



This example shows how to use a Parallel.ForEach loop to enable data parallelism over anySystem.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> data source.





 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ParallelLoopSample
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> Large_List1 = new List<string>();
            List<string> Large_List2 = new List<string>();
            Object myList = new Object();


            //Time taken by Loop to Write to List1
            var watch1 = Stopwatch.StartNew();

            for (Int64 i = 0; i <= 10000000; i++)
            {
                Large_List1.Add(i.ToString());
            }

            watch1.Stop();
            var elapsedMs = watch1.ElapsedMilliseconds;

            Console.WriteLine("Total Time Taken to Finish Loop1:{0}", elapsedMs);


            //Time Taken by Loop to Read List1 and Write to List2
            var watch2 = Stopwatch.StartNew();

            Parallel.ForEach(Large_List1, new ParallelOptions() { MaxDegreeOfParallelism = 10 }, sel =>
            {                
                try
                {
                    lock (myList)
                    {
                        Large_List2.Add(sel);
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

            });


            watch2.Stop();
            var elapsedMs2 = watch2.ElapsedMilliseconds;

            Console.WriteLine("Total Time Taken to Finish Loop2:{0}", elapsedMs2);

            Console.ReadLine();
        }
    }
}


Output:

No comments:

Post a Comment