Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

c# - Can I assign to a dictionary in parallel when that dictionary might resize?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...