TPL - ParallelUtility

Scenario:

Create utility to process data in parallel. Based on IDs, pull Users in parallel and then enqueue response and return back the list.

Solution:

ForEach takes list and Action to process the list and returns ParallelLoopResult. Add the result to ConcurrentQueue in thread safe visit. Then return/output list.
     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
    public class ParallelUtility
        {
            static void Main(string[] args)
            {
                var data = "1,2,3,4";
                var dataArray = data.Split(',');
    
                var dataReponseQueue = new ConcurrentQueue<string>();
    
                ForEach(dataArray, g =>
                {
                    var responses =
                        GetUsers(g.ToString());
    
                    foreach (var response in responses)
                    {
                        dataReponseQueue.Enqueue(response);
                    }
                });
    
                foreach (var item in dataReponseQueue.ToList())
                {
                    Console.WriteLine($"{item}");
                }
                Console.ReadLine();
            }
    
            private static string[] GetUsers(string i)
            {
                if (int.Parse(i) == 1)
                {
                    return new string[] { "Ram", "Shyam" };
                }
                else if (int.Parse(i) == 2)
                {
                    return new string[] { "Seeta", "Geeta" };
                }
                else if (int.Parse(i) == 3)
                {
                    return new string[] { "N/A" };
                }
                else
                {
                    return new string[] { "InValid" };
                }
            }
    
            public static ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> data, Action<TSource> body)
            {
                var result = Parallel.ForEach(data, o =>
                {
                    body(o);
                });
    
                return result;
            }
        }

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...