Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Threading.Tasks;
- namespace IteratorTests
- {
- public static class Program
- {
- public static void Main()
- {
- try
- {
- Test1();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.ToString());
- }
- Console.ReadKey();
- Console.WriteLine();
- try
- {
- Test2();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.ToString());
- }
- Console.ReadKey();
- Console.WriteLine();
- try
- {
- Test3();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.ToString());
- }
- Console.ReadKey();
- }
- private static void Test1()
- {
- var ten = RangeIterator(1, 10);
- Run(ten);
- }
- private static void Test2()
- {
- var ten = new [] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
- Run(ten);
- }
- private static void Test3()
- {
- var ten = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
- var counters = new ConcurrentDictionary<int, int>();
- Parallel.ForEach(ten, item => counters.AddOrUpdate(item, key => 1, (key, value) => ++value));
- foreach (var counter in counters)
- {
- Print(counter);
- }
- }
- private static void Run(IEnumerable<int> enumerator)
- {
- var counters = new ConcurrentDictionary<int, int>();
- var tasks = new List<Task>();
- for (int i = 0; i < 16; i++)
- {
- tasks.Add(Task.Run(() =>
- {
- foreach (var item in enumerator)
- {
- counters.AddOrUpdate(item, key => 1, (key, value) => ++value);
- }
- }));
- }
- Task.WaitAll(tasks.ToArray());
- foreach (var counter in counters)
- {
- Print(counter);
- }
- }
- private static void Print(KeyValuePair<int, int> pair)
- {
- Console.WriteLine($"{pair.Key}: {pair.Value}");
- }
- private static IEnumerable<int> RangeIterator(int start, int count)
- {
- for (var i = 0; i < count; i++)
- {
- yield return start + i;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement