Can I assign to a dictionary in parallel when that

2019-09-20 18:23发布

Based on another answer here: https://stackoverflow.com/a/8182978/369775

This claims that I cannot assign to a dictionary in parallel. I have never encountered an issue with assigning to a collection and worrying about its expanding its own size.

If I extend from that answer I think it says that I cannot do this contrived example:

Dictionary<int,int> foo = GetFoo();
var bar = new Dictionary<int,int>();

Parallel.ForEach(foo, bat=>
    {
        bar[bat.Key] = bat.Value
    }

This makes assignments to the dictionary in parallel the underlying collection bar might be resizing itself as needed.

It is very similar to what would be happening in this parallel assignment discussion from Jon skeet: Parallel Linq - Use more threads than processors (for non-CPU bound tasks)

I seems to me that I should not need to use a ConcurrentDictionary in the situation above but the answer I linked (from a notable user I respect) indicates otherwise.

Is it safe to use the Dictionary collection in the manner I described or will it fail?

Can somebody provide an code example where this sort of assigning will fail? I am trying to recognize the answers from SLaks and Jon Skeet with both explore assigning to a Dictionary in parallel.

EDIT Can the downvoter explain how I can improve my question? If what I'm asking is unlcear please explain how I can clarify. Thanks.

1条回答
神经病院院长
2楼-- · 2019-09-20 19:12

You cannot assign to a dictionary in parallel because the writes of the Dictionary class say it isn't thread safe. The details as to why aren't terribly important to the discussion.

If you are reading from a static dictionary you can do that from multiple threads as none of the reading options modify the underlying dictionary, but no updates are safe from multiple threads.

Feel free to walk through the logic and see why concurrent updates could fail if you want to know exactly why, but typically it is best to take the algorithm implementors word, as it is safer to assume someone else's logic was written with concurrent writing in mind it does not support it.

The simplest example of multiple writes failing is lines 352/353 which are (not so obviously) in the hot path for this method and involve copying a value followed by incrementing it.

查看更多
登录 后发表回答