多个计时器访问单个对象中的字典对象

use*_*606 0 c# multithreading timer

我有一个单例对象,并在其中定义了一个字典.

public class MyClass 
{
    public static readonly MyClass Instance = new MyClass();

    private MyClass
    {}

    public Dictionary<int, int> MyDictionary = new Dictionary<int, int>();
}
Run Code Online (Sandbox Code Playgroud)

现在,我有两个System.Timers.Timer对象更新MyDictionary.

System.Timers.Timer timer1 = new System.Timers.Timer(5);
timer1.AutoReset = false;
timer1.Elapsed += new System.Timers.ElapsedEventHandler(MyTimer1Handler);
timer1.Enabled = true;
timer1.Start();

System.Timers.Timer timer2 = new System.Timers.Timer(5);
timer2.AutoReset = false;
timer2.Elapsed += new System.Timers.ElapsedEventHandler(MyTimer2Handler);
timer2.Enabled = true;
timer2.Start();

private void MyTimer1Handler(object sender, ElapsedEventArgs e)
{
     MyClass.Instance.MyDictonary[1] = 100;
}

private void MyTimer1Handler(object sender, ElapsedEventArgs e)
{
     MyClass.Instance.MyDictonary[2] = 100;
}
Run Code Online (Sandbox Code Playgroud)

我现在的问题是,考虑到定时器的已用事件处理程序在MyDictionary的索引1和索引2上唯一操作,我是否需要对MyDictionary进行任何锁定?

Mat*_*ttW 5

是的,你必须.

http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

这表示阅读是线程安全的,但编辑不是.它还表示迭代它并不是真的安全Dictionary.

如果您能够使用.NET 4,则可以使用a ConcurrentDictionary,这是线程安全的.

http://msdn.microsoft.com/en-us/library/dd287191.aspx