I am doing this:
private static void Main(string[] args)
{
var dict1 = new Dictionary<int, string>();
var dict2 = new Dictionary<int, string>();
DateTime t1 = DateTime.Now;
for (int i = 1; i < 1000000; i++)
{
Parallel.Invoke(
() => dict1.Add(i, "Test" + i),
() => dict2.Add(i, "Test" + i) );
}
TimeSpan t2 = DateTime.Now.Subtract(t1);
Console.WriteLine(t2.TotalMilliseconds);
Console.ReadLine();
}
So doing a for loop 1 million time and adding items to two different dictionaries.
The problem is that it takes 11 secs which is more than 5 time the normal sequential method (without tasks/threads) which takes only 2 sec.
Don’t know why.
Like others have said or implied, parallel code is not always faster due to the overhead of parallelization.
That being said, your code is adding an item to 2 dictionaries in parallel 1M times while you should be adding 1M items to 2 dictionaries in parallel. The difference is subtle but the end result is code that is ~10% faster (on my machine) than your sequential case.