我想知道这段代码是否是线程安全的,为什么不是这样。

    static IMyInterface _myinterface;
        public static IMyInterface someStuff
        {
            get
            {
                if (_myinterface== null)
                {
                    _myinterface= MyServiceLocator.GetCurrent().GetInstance<IMyInterface>();
                }

                return _myinterface;
            }
        }


谢谢!

最佳答案

否。您需要使用锁。

private static readonly object m_lock = new object();
private static IMyInterface _myinterface;

public static IMyInterface someStuff
{
    get
    {
        lock(m_lock)
        {
           if (_myinterface == null)
           {
             //create instance
           }

           return _myinterface;
        }
    }
}

10-04 12:56