Advertisement
Guest User

Untitled

a guest
Feb 9th, 2016
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Threading.Tasks;
  5.  
  6. namespace IteratorTests
  7. {
  8. public static class Program
  9. {
  10. public static void Main()
  11. {
  12. try
  13. {
  14. Test1();
  15. }
  16. catch (Exception ex)
  17. {
  18. Console.WriteLine(ex.ToString());
  19. }
  20.  
  21. Console.ReadKey();
  22. Console.WriteLine();
  23.  
  24. try
  25. {
  26. Test2();
  27. }
  28. catch (Exception ex)
  29. {
  30. Console.WriteLine(ex.ToString());
  31. }
  32.  
  33.  
  34. Console.ReadKey();
  35. Console.WriteLine();
  36.  
  37. try
  38. {
  39. Test3();
  40. }
  41. catch (Exception ex)
  42. {
  43. Console.WriteLine(ex.ToString());
  44. }
  45.  
  46.  
  47. Console.ReadKey();
  48. }
  49.  
  50. private static void Test1()
  51. {
  52. var ten = RangeIterator(1, 10);
  53.  
  54. Run(ten);
  55. }
  56.  
  57. private static void Test2()
  58. {
  59. var ten = new [] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  60.  
  61. Run(ten);
  62. }
  63.  
  64. private static void Test3()
  65. {
  66. var ten = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  67.  
  68. var counters = new ConcurrentDictionary<int, int>();
  69. Parallel.ForEach(ten, item => counters.AddOrUpdate(item, key => 1, (key, value) => ++value));
  70. foreach (var counter in counters)
  71. {
  72. Print(counter);
  73. }
  74. }
  75.  
  76. private static void Run(IEnumerable<int> enumerator)
  77. {
  78. var counters = new ConcurrentDictionary<int, int>();
  79.  
  80. var tasks = new List<Task>();
  81. for (int i = 0; i < 16; i++)
  82. {
  83. tasks.Add(Task.Run(() =>
  84. {
  85. foreach (var item in enumerator)
  86. {
  87. counters.AddOrUpdate(item, key => 1, (key, value) => ++value);
  88. }
  89. }));
  90. }
  91.  
  92. Task.WaitAll(tasks.ToArray());
  93.  
  94. foreach (var counter in counters)
  95. {
  96. Print(counter);
  97. }
  98. }
  99.  
  100. private static void Print(KeyValuePair<int, int> pair)
  101. {
  102. Console.WriteLine($"{pair.Key}: {pair.Value}");
  103. }
  104.  
  105. private static IEnumerable<int> RangeIterator(int start, int count)
  106. {
  107. for (var i = 0; i < count; i++)
  108. {
  109. yield return start + i;
  110. }
  111. }
  112. }
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement