baozi
baozi

Reputation: 709

How to use parallel.for to add item to list

I came from Threading with Parallel.For Adding Lists . For the example in the link two threads are used to call Parallel.Invoke which is still slow so I'd like to do some multi-threading inside the loop assuming i do not care the order items are added. But the parallel.for did not work as expecetd and gives indexoutofRange exception. Someone plz help?

private static void Main(string[] args)
{
    var dict1 = new Dictionary<int, string>();
    var dict2 = new Dictionary<int, string>();
    Stopwatch s = Stopwatch.StartNew();
    Parallel.Invoke(() => FillDictionary(dict1, 10000000), () => FillDictionary(dict2, 10000000));
    //FillDictionary(dict1, 10000000);
    //FillDictionary(dict2, 10000000);
    Console.WriteLine("test");
    Console.WriteLine(s.Elapsed.TotalMilliseconds);
    Console.ReadLine();
}
private static void FillDictionary(Dictionary<int, string> toFill, int itemCount)
{
    //for (int i = 0; i < itemCount; i++)
        //toFill.Add(i, "test" + i);
    Parallel.For(0, itemCount, (i) => toFill.Add(i, "test" + i));    
}

Upvotes: 1

Views: 1072

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Dictionary is not thread safe.Use ConcurrentDictionary<TKey, TValue> instead.

Upvotes: 4

Related Questions