سؤال

I have the following code:

Dictionary<string, WSResponse> responseDictionary = new Dictionary<string, WSResponse>();
List<Task> taskList = new List<Task>();
            foreach (string ID in IDs)
            {
                string localID = ID;

                Task newTask = Task.Factory.StartNew(() =>
                {
                    WSResponse response = Query.GetListFor(localID);                    
                    responseDictionary.Add(localID, response);
                });
                taskList.Add(newTask);
            }


            Task.WaitAll(taskList.ToArray());

Should I be using a ConcurrentDictionary instead of a Dictionary in this case? Even if I make sure keys do not repeate on the logical level?

هل كانت مفيدة؟

المحلول

ConcurrentDictionary and locking are NOT interchangeable or equivalent.

Adding a lock will force all tasks to write to the dictionary sequentially, essentially negating any benefits you may have from concurrent processing. The Dictionary class will also throw a somewhat cryptic exception if more than two threads try to write to it concurrently. This is because unlocked access will corrupt its internal structures.

A ConcurrentDictionary on the other hand allows all tasks to write to the dictionary concurrently without any need of locking. The penalty is slower synchronous performance compared to the unlocked synchronous version. In concurrent scenarios though, performance and scalability are much better.

نصائح أخرى

You should use syncronization, yes. A simple lock would be enough.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top