Mercurial > pub > ImplabNet
comparison Implab/Components/LazyAndWeak.cs @ 180:c32688129f14 ref20160224
refactoring complete, JSONParser rewritten
author | cin |
---|---|
date | Thu, 24 Mar 2016 02:30:46 +0300 |
parents | d5c5db0335ee |
children | 76e8f2ba12b8 |
comparison
equal
deleted
inserted
replaced
179:478ef706906a | 180:c32688129f14 |
---|---|
1 using System; | 1 using System; |
2 using System.Threading; | 2 using System.Threading; |
3 | 3 |
4 namespace Implab.Components { | 4 namespace Implab.Components { |
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> | |
5 public class LazyAndWeak<T> where T : class { | 12 public class LazyAndWeak<T> where T : class { |
6 | 13 |
7 readonly Func<T> m_factory; | 14 readonly Func<T> m_factory; |
8 readonly object m_lock; | 15 readonly object m_lock; |
9 WeakReference m_reference; | 16 WeakReference m_reference; |
33 value = m_factory(); | 40 value = m_factory(); |
34 | 41 |
35 if (Interlocked.CompareExchange(ref m_reference, new WeakReference(value), weak) == weak) | 42 if (Interlocked.CompareExchange(ref m_reference, new WeakReference(value), weak) == weak) |
36 return value; | 43 return value; |
37 } else { | 44 } else { |
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 } | |
38 } | 57 } |
39 } | 58 } |
40 } | 59 } |
41 } | 60 } |
42 } | 61 } |