LazyOfT Implementation: Double Checked Locking

Nov 18, 2010 at 3:17 PM

Looking at:

http://mef.codeplex.com/SourceControl/changeset/view/34058#484572

Isn't there a second check on isValueCreated after the Monitor.Enter neccessary? Otherwise a second thread could see isValueCreated=true and wait before the Monitor.Enter. Then after the first thread created the value and exited the Monitor the second thread would enter an cause a NPE since the _valueFactory is now null.

 

public T Value
        {
            get
            {
                if (!this._isValueCreated)
                {
                    if(this._lock != null)
                    {
                        Monitor.Enter(this._lock);
                    }

                    try
                    {
                        if (!this._isValueCreated)
                        {
                          T value = this._valueFactory.Invoke();
                          this._valueFactory = null;
                          Thread.MemoryBarrier();
                          this._value = value;
                          this._isValueCreated = true;
                        }
                    }
                    finally
                    {
                        if(this._lock != null)
                        {
                            Monitor.Exit(this._lock);
                        }
                    }
                }
                return this._value;
            }
        }