blob: 6d3b11acfb3cd2cdf80db7d963b9c56a56ac8874 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
// -----------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// -----------------------------------------------------------------------
#if !CLR40
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.Internal;
namespace System
{
public class Lazy<T>
{
private T _value = default(T);
private volatile bool _isValueCreated = false;
private Func<T> _valueFactory = null;
private object _lock;
public Lazy()
: this(() => Activator.CreateInstance<T>())
{
}
public Lazy(bool isThreadSafe)
: this(() => Activator.CreateInstance<T>(), isThreadSafe)
{
}
public Lazy(Func<T> valueFactory):
this(valueFactory, true)
{
}
public Lazy(Func<T> valueFactory, bool isThreadSafe)
{
Requires.NotNull(valueFactory, "valueFactory");
if(isThreadSafe)
{
this._lock = new object();
}
this._valueFactory = valueFactory;
}
public T Value
{
get
{
if (!this._isValueCreated)
{
if(this._lock != null)
{
Monitor.Enter(this._lock);
}
try
{
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;
}
}
}
}
#endif
|