comparison Implab/Components/LazyAndWeak.cs @ 178:d5c5db0335ee ref20160224

working on JSON parser
author cin
date Wed, 23 Mar 2016 19:51:45 +0300
parents
children c32688129f14
comparison
equal deleted inserted replaced
177:a0ff6a0e9c44 178:d5c5db0335ee
1 using System;
2 using System.Threading;
3
4 namespace Implab.Components {
5 public class LazyAndWeak<T> where T : class {
6
7 readonly Func<T> m_factory;
8 readonly object m_lock;
9 WeakReference m_reference;
10
11
12 public LazyAndWeak(Func<T> factory, bool useLock) {
13 Safe.ArgumentNotNull(factory, "factory");
14 m_factory = factory;
15 m_lock = useLock ? new object() : null;
16 }
17
18 public LazyAndWeak(Func<T> factory) : this(factory, false) {
19 }
20
21 public T Value {
22 get {
23 while (true) {
24 var weak = m_reference;
25 T value;
26 if (weak != null) {
27 value = weak.Target as T;
28 if (value != null)
29 return value;
30 }
31
32 if (m_lock == null) {
33 value = m_factory();
34
35 if (Interlocked.CompareExchange(ref m_reference, new WeakReference(value), weak) == weak)
36 return value;
37 } else {
38 }
39 }
40 }
41 }
42 }
43 }
44