Should this class use data locking for multi threading?

后端 未结 3 1359
名媛妹妹
名媛妹妹 2021-01-21 20:55

I have a class that contains some data and there are many threads use it:

class MyClass
{
    static Dictionary MyData;

    static IEnumerable         


        
3条回答
  •  不要未来只要你来
    2021-01-21 21:14

    I disagree with Richard. You seem to use the Dictionary<,> in an immutable fashion, never changing the content. It is returned completely populated from the GetMyData() method and simply replaces a reference on MyData, while only exposing the immutable Values property. Even if someone is enumerating over the dictionary while someone else calls Reset(), the person will continue enumerating over the old dictionary while any new reader will get the new dictionary. So your code is completely thread-safe, thanks to the fact that that you use data structures as if they were immutable. You might want to wrap it in a real immutable dictionary (e.g. from here) If, on the other hand, there are different usages in other parts of the code that we can't see, then it would be a different matter.

    EDIT: I just noticed that both MyData and Data are private (then why even bother with an extra property?), so you're also might be using MyData to modify the dictionary. In that case, as long as all the dictionary read/writes happen on the same thread, but the Reset() method is called from a different thread, then you're okay. If, on the other hand, you're modifying the collection on one thread while reading from it on another thread, then you'll have to perform manual synchronization as Richard mentioned. The point is that the Reset() method is never the issue, since it replaces the reference of the dictionary with a new instance without affecting the old instance.

提交回复
热议问题