82
|
1 using System;
|
|
2 using Implab.Parallels;
|
|
3 using System.Threading;
|
85
|
4 using System.Diagnostics;
|
|
5 using System.Diagnostics.CodeAnalysis;
|
82
|
6
|
|
7 namespace Implab {
|
85
|
8 public abstract class ObjectPool<T> : IDisposable {
|
82
|
9 readonly int m_size;
|
|
10 readonly MTQueue<T> m_queue = new MTQueue<T>();
|
|
11
|
85
|
12 [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
|
|
13 static readonly bool _isValueType = typeof(T).IsValueType;
|
|
14
|
83
|
15 bool m_disposed;
|
82
|
16
|
83
|
17 int m_count;
|
82
|
18
|
85
|
19 protected ObjectPool(int size) {
|
82
|
20 m_size = size;
|
|
21 }
|
|
22
|
85
|
23 protected ObjectPool() : this(Environment.ProcessorCount+1) {
|
82
|
24 }
|
|
25
|
83
|
26 public T Allocate() {
|
82
|
27 if (m_disposed)
|
85
|
28 throw new ObjectDisposedException(ToString());
|
82
|
29
|
|
30 T instance;
|
|
31 if (m_queue.TryDequeue(out instance)) {
|
|
32 Interlocked.Decrement(ref m_count);
|
|
33 } else {
|
85
|
34 instance = CreateInstance();
|
|
35 Debug.Assert(!Object.Equals(instance, default(T)) || _isValueType);
|
82
|
36 }
|
83
|
37 return instance;
|
82
|
38 }
|
|
39
|
85
|
40 protected abstract T CreateInstance();
|
|
41
|
|
42 protected virtual void CleanupInstance(T instance) {
|
|
43 }
|
|
44
|
82
|
45 public void Release(T instance) {
|
85
|
46 if ( Object.Equals(instance,default(T)) && !_isValueType)
|
|
47 return;
|
|
48
|
83
|
49 Thread.MemoryBarrier();
|
82
|
50 if (m_count < m_size && !m_disposed) {
|
|
51 Interlocked.Increment(ref m_count);
|
|
52
|
85
|
53 CleanupInstance(instance);
|
82
|
54
|
|
55 m_queue.Enqueue(instance);
|
|
56
|
|
57 // пока элемент возвращался в кеш, была начата операция освобождения всего кеша
|
|
58 // и возможно уже законцена, в таком случае следует извлечь элемент обратно и
|
|
59 // освободить его. Если операция освобождения кеша еще не заврешилась, то будет
|
|
60 // изъят и освобожден произвольный элемен, что не повлияет на ход всего процесса.
|
83
|
61 if (m_disposed && m_queue.TryDequeue(out instance) && instance is IDisposable)
|
|
62 ((IDisposable)instance).Dispose() ;
|
82
|
63
|
|
64 } else {
|
83
|
65 if (instance is IDisposable)
|
|
66 ((IDisposable)instance).Dispose();
|
82
|
67 }
|
|
68 }
|
|
69
|
|
70 protected virtual void Dispose(bool disposing) {
|
|
71 if (disposing) {
|
|
72 m_disposed = true;
|
|
73 T instance;
|
|
74 while (m_queue.TryDequeue(out instance))
|
83
|
75 if (instance is IDisposable)
|
|
76 ((IDisposable)instance).Dispose();
|
82
|
77 }
|
|
78 }
|
|
79
|
|
80 #region IDisposable implementation
|
|
81
|
|
82 public void Dispose() {
|
|
83 Dispose(true);
|
|
84 GC.SuppressFinalize(this);
|
|
85 }
|
|
86
|
|
87 #endregion
|
|
88 }
|
|
89 }
|
|
90
|