如果这个类使用的数据锁定的多线程? [英] Should this class use data locking for multi threading?

查看:146
本文介绍了如果这个类使用的数据锁定的多线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些数据的类,并有许多线程使用它:

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

class MyClass
{
    static Dictionary<Key, Value> MyData;

    static IEnumerable<Data> Data
    {
        get
        {
            return MyData.Values;
        }
    }

    static void Reset()
    {
         MyData = GetMyData();
    }
}

有时(比如一次一天)的复位方法被调用。我不想加入,因为业绩锁定,但不能肯定是否一切都将离不开它了。

Sometime (say once in a day) the Reset method is called. I don't want to add locking because of performance, but not sure if everything will work without it.

现在的问题是:我应该使用任何类型的锁在这个类的

The question is: should I use any type of locking in this class?

推荐答案

我不同意理查德。你似乎使用词典&LT;,&GT; 在一个不变的时尚,永不改变的内容。它返回完全填充的 GetMyData()的方法,简单地取代了迈德特一个参考,而只露出不变财产。即使有人列举了字典,而别人通话重置(),此人将继续列举了旧字典,而任何新的读者将获得新的字典。所以,你的code是完全线程安全的,这要感谢您使用的数据结构,好像他们是不可改变的事实。您可能希望把它包在一个真正的不可变的字典(如<一个href="http://stackoverflow.com/questions/35002/does-c-have-a-way-of-giving-me-an-immutable-dictionary">from这里)如果,另一方面,也有在的code,我们不能看到其他部分不同的用途,那么这将是一个不同的问题。

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.

编辑:我刚才注意到,这两个迈德特数据是私有的(那么为什么还要有额外的属性打扰?),所以你也可能会使用迈德特修改字典。在这种情况下,只要所有的词典读/写操作发生在同一个线程,但重置()方法是从不同的线程调用,那么你没事。如果,另一方面,你正在修改的集合在一个线程,而从中读取另一个线程,那么你就必须执行手动同步理查德提及。问题的关键是,复位()方法从来都不是问题,因为它取代了新的实例字典的参考,而不会影响旧的实例。

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.

这篇关于如果这个类使用的数据锁定的多线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆