Created
February 9, 2016 09:52
-
-
Save denisivan0v/b53e0f5269e573a6cc56 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment