forked from divyang4481/objectpool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DisposableObject.cs
122 lines (109 loc) · 3.12 KB
/
DisposableObject.cs
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
using System;
using System.Threading;
using System.Collections.Generic;
using SystemUtilities.Threading;
namespace SystemUtilities
{
[Serializable]
public abstract class DisposableObject : IDisposable
{
[NonSerialized]
private bool _disposed;
[NonSerialized]
private ICollection<OnDisposedEventHandler> _handlers;
#region IDisposable Members
public event OnDisposedEventHandler Disposed
{
add
{
ExceptionHelper.ThrowIfDisposed(this);
if (_handlers == null)
{
Monitor.Enter(this);
{
try
{
if (_handlers == null)
{
_handlers = new List<OnDisposedEventHandler>();
}
}
finally
{
Monitor.Exit(this);
}
}
}
_handlers.Add(value);
}
remove
{
if (_handlers != null)
{
Monitor.Enter(this);
try
{
_handlers.Remove(value);
}
finally
{
Monitor.Exit(this);
}
}
}
}
public virtual bool IsDisposed
{
get { return _disposed; }
}
#endregion
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (!IsDisposed)
{
_disposed = true;
OnDisposed(new OnDisposedEventArgs());
}
}
}
#region System.IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
~DisposableObject()
{
Dispose(false);
}
protected virtual void OnDisposed(OnDisposedEventArgs e)
{
OnDisposedEventHandler[] handlers = null;
Monitor.Enter(this);
try
{
if (_handlers != null)
{
handlers = new OnDisposedEventHandler[_handlers.Count];
_handlers.CopyTo(handlers, 0);
_handlers.Clear();
}
}
finally
{
Monitor.Exit(this);
}
if (handlers != null)
{
foreach (OnDisposedEventHandler handler in handlers)
{
if (handler != null)
AsyncHelper.FireAndForget(handler, this, e);
}
}
}
}
}