178
|
1 using System;
|
|
2 using System.Threading;
|
|
3
|
|
4 namespace Implab.Components {
|
180
|
5 /// <summary>
|
|
6 /// Creates an instace on-demand and allows it to be garbage collected.
|
|
7 /// </summary>
|
|
8 /// <remarks>
|
|
9 /// Usefull when dealing with memory-intensive objects which are frequently used.
|
|
10 /// This class is similar to <see cref="ObjectPool{T}"/> except is a singleton.
|
|
11 /// </remarks>
|
178
|
12 public class LazyAndWeak<T> where T : class {
|
|
13
|
|
14 readonly Func<T> m_factory;
|
|
15 readonly object m_lock;
|
|
16 WeakReference m_reference;
|
|
17
|
|
18
|
|
19 public LazyAndWeak(Func<T> factory, bool useLock) {
|
|
20 Safe.ArgumentNotNull(factory, "factory");
|
|
21 m_factory = factory;
|
|
22 m_lock = useLock ? new object() : null;
|
|
23 }
|
|
24
|
|
25 public LazyAndWeak(Func<T> factory) : this(factory, false) {
|
|
26 }
|
|
27
|
|
28 public T Value {
|
|
29 get {
|
|
30 while (true) {
|
|
31 var weak = m_reference;
|
|
32 T value;
|
|
33 if (weak != null) {
|
|
34 value = weak.Target as T;
|
|
35 if (value != null)
|
|
36 return value;
|
|
37 }
|
|
38
|
|
39 if (m_lock == null) {
|
|
40 value = m_factory();
|
|
41
|
|
42 if (Interlocked.CompareExchange(ref m_reference, new WeakReference(value), weak) == weak)
|
|
43 return value;
|
|
44 } else {
|
180
|
45 lock (m_lock) {
|
|
46 // double check
|
|
47 if (weak != null) {
|
|
48 value = weak.Target as T;
|
|
49 if (value != null)
|
|
50 return value;
|
|
51 }
|
|
52 // we are safe to write
|
|
53 value = m_factory();
|
|
54 m_reference = new WeakReference(value);
|
|
55 return value;
|
|
56 }
|
178
|
57 }
|
|
58 }
|
|
59 }
|
|
60 }
|
|
61 }
|
|
62 }
|
|
63
|