forked from reactiveui/ReactiveUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeakEventManager.cs
More file actions
370 lines (309 loc) · 14 KB
/
WeakEventManager.cs
File metadata and controls
370 lines (309 loc) · 14 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MS-PL license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Disposables;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
namespace ReactiveUI
{
#if !NET_45
internal class CanExecuteChangedEventManager : WeakEventManager<ICommand, EventHandler, EventArgs>
{
}
internal class PropertyChangingEventManager : WeakEventManager<INotifyPropertyChanging, PropertyChangingEventHandler, PropertyChangingEventArgs>
{
}
internal class PropertyChangedEventManager : WeakEventManager<INotifyPropertyChanged, PropertyChangedEventHandler, PropertyChangedEventArgs>
{
}
internal class CollectionChangingEventManager : WeakEventManager<INotifyCollectionChanging, NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>
{
}
internal class CollectionChangedEventManager : WeakEventManager<INotifyCollectionChanged, NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>
{
}
#endif
/// <summary>
/// WeakEventManager base class. Inspired by the WPF WeakEventManager class and the code in
/// http://social.msdn.microsoft.com/Forums/silverlight/en-US/34d85c3f-52ea-4adc-bb32-8297f5549042/command-binding-memory-leak?forum=silverlightbugs
/// </summary>
/// <typeparam name="TEventSource">The type of the event source.</typeparam>
/// <typeparam name="TEventHandler">The type of the event handler.</typeparam>
/// <typeparam name="TEventArgs">The type of the event arguments.</typeparam>
public class WeakEventManager<TEventSource, TEventHandler, TEventArgs>
{
static readonly object StaticSource = new object();
/// <summary>
/// Mapping between the target of the delegate (for example a Button) and the handler (EventHandler).
/// Windows Phone needs this, otherwise the event handler gets garbage collected.
/// </summary>
ConditionalWeakTable<object, List<Delegate>> targetToEventHandler = new ConditionalWeakTable<object, List<Delegate>>();
/// <summary>
/// Mapping from the source of the event to the list of handlers. This is a CWT to ensure it does not leak the source of the event.
/// </summary>
ConditionalWeakTable<object, WeakHandlerList> sourceToWeakHandlers = new ConditionalWeakTable<object, WeakHandlerList>();
static Lazy<WeakEventManager<TEventSource, TEventHandler, TEventArgs>> current =
new Lazy<WeakEventManager<TEventSource, TEventHandler, TEventArgs>>(() => new WeakEventManager<TEventSource, TEventHandler, TEventArgs>());
static WeakEventManager<TEventSource, TEventHandler, TEventArgs> Current {
get { return current.Value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="WeakEventManager{TEventSource, TEventHandler, TEventArgs}"/> class.
/// Protected to disallow instances of this class and force a subclass.
/// </summary>
protected WeakEventManager()
{
}
/// <summary>
/// Adds a weak reference to the handler and associates it with the source.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="handler">The handler.</param>
public static void AddHandler(TEventSource source, TEventHandler handler)
{
if (source == null) throw new ArgumentNullException("source");
if (handler == null) throw new ArgumentNullException("handler");
if (!typeof(TEventHandler).GetTypeInfo().IsSubclassOf(typeof(Delegate))) {
throw new ArgumentException("Handler must be Delegate type");
}
WeakEventManager<TEventSource, TEventHandler, TEventArgs>.Current.PrivateAddHandler(source, handler);
}
/// <summary>
/// Removes the association between the source and the handler.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="handler">The handler.</param>
public static void RemoveHandler(TEventSource source, TEventHandler handler)
{
if (source == null) throw new ArgumentNullException("source");
if (handler == null) throw new ArgumentNullException("handler");
if (!typeof(TEventHandler).GetTypeInfo().IsSubclassOf(typeof(Delegate))) {
throw new ArgumentException("handler must be Delegate type");
}
WeakEventManager<TEventSource, TEventHandler, TEventArgs>.Current.PrivateRemoveHandler(source, handler);
}
/// <summary>
/// Delivers the event to the handlers registered for the source.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="TEventArgs"/> instance containing the event data.</param>
public static void DeliverEvent(TEventSource sender, TEventArgs args)
{
WeakEventManager<TEventSource, TEventHandler, TEventArgs>.Current.PrivateDeliverEvent(sender, args);
}
/// <summary>
/// Override this method to attach to an event.
/// </summary>
/// <param name="source">The source.</param>
protected virtual void StartListening(object source)
{
}
/// <summary>
/// Override this method to detach from an event.
/// </summary>
/// <param name="source">The source.</param>
protected virtual void StopListening(object source)
{
}
void PrivateAddHandler(TEventSource source, TEventHandler handler)
{
this.AddWeakHandler(source, handler);
this.AddTargetHandler(handler);
}
void AddWeakHandler(TEventSource source, TEventHandler handler)
{
WeakHandlerList weakHandlers;
if (this.sourceToWeakHandlers.TryGetValue(source, out weakHandlers)) {
// clone list if we are currently delivering an event
if (weakHandlers.IsDeliverActive) {
weakHandlers = weakHandlers.Clone();
this.sourceToWeakHandlers.Remove(source);
this.sourceToWeakHandlers.Add(source, weakHandlers);
}
weakHandlers.AddWeakHandler(source, handler);
} else {
weakHandlers = new WeakHandlerList();
weakHandlers.AddWeakHandler(source, handler);
this.sourceToWeakHandlers.Add(source, weakHandlers);
this.StartListening(source);
}
this.Purge(source);
}
void AddTargetHandler(TEventHandler handler)
{
var @delegate = handler as Delegate;
object key = @delegate.Target ?? WeakEventManager<TEventSource, TEventHandler, TEventArgs>.StaticSource;
List<Delegate> delegates;
if (this.targetToEventHandler.TryGetValue(key, out delegates)) {
delegates.Add(@delegate);
} else {
delegates = new List<Delegate>();
delegates.Add(@delegate);
this.targetToEventHandler.Add(key, delegates);
}
}
void PrivateRemoveHandler(TEventSource source, TEventHandler handler)
{
this.RemoveWeakHandler(source, handler);
this.RemoveTargetHandler(handler);
}
void RemoveWeakHandler(TEventSource source, TEventHandler handler)
{
var weakHandlers = default(WeakHandlerList);
if (this.sourceToWeakHandlers.TryGetValue(source, out weakHandlers)) {
// clone list if we are currently delivering an event
if (weakHandlers.IsDeliverActive) {
weakHandlers = weakHandlers.Clone();
this.sourceToWeakHandlers.Remove(source);
this.sourceToWeakHandlers.Add(source, weakHandlers);
}
if (weakHandlers.RemoveWeakHandler(source, handler) && weakHandlers.Count == 0) {
this.sourceToWeakHandlers.Remove(source);
this.StopListening(source);
}
}
}
void RemoveTargetHandler(TEventHandler handler)
{
var @delegate = handler as Delegate;
object key = @delegate.Target ?? WeakEventManager<TEventSource, TEventHandler, TEventArgs>.StaticSource;
var delegates = default(List<Delegate>);
if (this.targetToEventHandler.TryGetValue(key, out delegates)) {
delegates.Remove(@delegate);
if (delegates.Count == 0) {
this.targetToEventHandler.Remove(key);
}
}
}
void PrivateDeliverEvent(object sender, TEventArgs args)
{
object source = sender != null ? sender : WeakEventManager<TEventSource, TEventHandler, TEventArgs>.StaticSource;
var weakHandlers = default(WeakHandlerList);
bool hasStaleEntries = false;
if (this.sourceToWeakHandlers.TryGetValue(source, out weakHandlers)) {
using (weakHandlers.DeliverActive()) {
hasStaleEntries = weakHandlers.DeliverEvent(source, args);
}
}
if (hasStaleEntries) {
this.Purge(source);
}
}
void Purge(object source)
{
var weakHandlers = default(WeakHandlerList);
if (this.sourceToWeakHandlers.TryGetValue(source, out weakHandlers)) {
if (weakHandlers.IsDeliverActive) {
weakHandlers = weakHandlers.Clone();
this.sourceToWeakHandlers.Remove(source);
this.sourceToWeakHandlers.Add(source, weakHandlers);
} else {
weakHandlers.Purge();
}
}
}
internal class WeakHandler
{
WeakReference source;
WeakReference originalHandler;
public bool IsActive {
get { return this.source != null && this.source.IsAlive && this.originalHandler != null && this.originalHandler.IsAlive; }
}
public TEventHandler Handler {
get {
if (this.originalHandler == null) {
return default(TEventHandler);
} else {
return (TEventHandler)this.originalHandler.Target;
}
}
}
public WeakHandler(object source, TEventHandler originalHandler)
{
this.source = new WeakReference(source);
this.originalHandler = new WeakReference(originalHandler);
}
public bool Matches(object source, TEventHandler handler)
{
return this.source != null &&
Object.ReferenceEquals(this.source.Target, source) &&
this.originalHandler != null &&
(Object.ReferenceEquals(this.originalHandler.Target, handler) ||
(this.originalHandler.Target is PropertyChangedEventHandler &&
handler is PropertyChangedEventHandler &&
object.Equals((this.originalHandler.Target as PropertyChangedEventHandler).Target,
(handler as PropertyChangedEventHandler).Target)));
}
}
internal class WeakHandlerList
{
int deliveries = 0;
List<WeakHandler> handlers;
public WeakHandlerList()
{
handlers = new List<WeakHandler>();
}
public void AddWeakHandler(TEventSource source, TEventHandler handler)
{
WeakHandler handlerSink = new WeakHandler(source, handler);
handlers.Add(handlerSink);
}
public bool RemoveWeakHandler(TEventSource source, TEventHandler handler)
{
foreach (var weakHandler in handlers) {
if (weakHandler.Matches(source, handler)) {
return handlers.Remove(weakHandler);
}
}
return false;
}
public WeakHandlerList Clone()
{
WeakHandlerList newList = new WeakHandlerList();
newList.handlers.AddRange(this.handlers.Where(h => h.IsActive));
return newList;
}
public int Count {
get { return this.handlers.Count; }
}
public bool IsDeliverActive {
get { return this.deliveries > 0; }
}
public IDisposable DeliverActive()
{
Interlocked.Increment(ref this.deliveries);
return Disposable.Create(() => Interlocked.Decrement(ref this.deliveries));
}
public virtual bool DeliverEvent(object sender, TEventArgs args)
{
bool hasStaleEntries = false;
foreach (var handler in handlers) {
if (handler.IsActive) {
var @delegate = handler.Handler as Delegate;
@delegate.DynamicInvoke(sender, args);
} else {
hasStaleEntries = true;
}
}
return hasStaleEntries;
}
public void Purge()
{
for (int i = handlers.Count - 1; i >= 0; i--) {
if(!handlers[i].IsActive) {
handlers.RemoveAt(i);
}
}
}
}
}
}