单例类的构造函数被调用两次

时间:2014-10-01 13:21:17

标签: c# multithreading singleton

我正在读代码,有一个像这样的单例类:

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

    private Employee()
    {
        /* This messageBox shows different numbers */
        MessageBox.Show("Thread ID " + Thread.CurrentThread.ManagedThreadId);
    }
}

此类的构造函数在同一进程中被调用两次,而不创建另一个Domain。构造函数中的messageBox显示两个不同的数字。可能还是我错了?

注意:我在c ++项目中托管我的可执行程序集,但没有不同之处,许多大型项目都正常工作。

1 个答案:

答案 0 :(得分:-1)

这解决了你的问题,但单例的实现太错了。

class Employee
{
    private static Employee _instance;
    private static object syncRoot = new Object();

    public static Employee Instance
    {
        get
        {
            lock (syncRoot) 
            {
                if (_instance != null)
                    _instance = new Employee();
            }   
            return _instance;
        }
    }

    private Employee()
    {
        /* This messageBox shows different numbers */
        MessageBox.Show("Thread ID " + Thread.CurrentThread.ManagedThreadId);
    }
}
相关问题