1 // -----------------------------------------------------------------------
\r
2 // Copyright (c) Microsoft Corporation. All rights reserved.
\r
3 // -----------------------------------------------------------------------
\r
6 using System.Collections.Generic;
\r
9 using System.Threading;
\r
10 using Microsoft.Internal;
\r
14 public class Lazy<T>
\r
16 private T _value = default(T);
\r
17 private volatile bool _isValueCreated = false;
\r
18 private Func<T> _valueFactory = null;
\r
19 private object _lock;
\r
22 : this(() => Activator.CreateInstance<T>())
\r
26 public Lazy(bool isThreadSafe)
\r
27 : this(() => Activator.CreateInstance<T>(), isThreadSafe)
\r
31 public Lazy(Func<T> valueFactory):
\r
32 this(valueFactory, true)
\r
36 public Lazy(Func<T> valueFactory, bool isThreadSafe)
\r
38 Requires.NotNull(valueFactory, "valueFactory");
\r
41 this._lock = new object();
\r
44 this._valueFactory = valueFactory;
\r
52 if (!this._isValueCreated)
\r
54 if(this._lock != null)
\r
56 Monitor.Enter(this._lock);
\r
61 T value = this._valueFactory.Invoke();
\r
62 this._valueFactory = null;
\r
63 Thread.MemoryBarrier();
\r
64 this._value = value;
\r
65 this._isValueCreated = true;
\r
69 if(this._lock != null)
\r
71 Monitor.Exit(this._lock);
\r