-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathEventManager.cs
More file actions
81 lines (72 loc) · 2.95 KB
/
Copy pathEventManager.cs
File metadata and controls
81 lines (72 loc) · 2.95 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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using GeneralUpdate.Core;
namespace GeneralUpdate.Core.Event
{
/// <summary>
/// Thread-safe event manager using ConcurrentDictionary.
/// Supports add/remove/dispatch without lock contention.
/// </summary>
public class EventManager : IDisposable
{
private static readonly Lazy<EventManager> _lazy = new(() => new EventManager());
private ConcurrentDictionary<Type, Delegate> _dicDelegates = new();
private bool _disposed;
private EventManager() { }
public static EventManager Instance => _lazy.Value;
public void AddListener<TEventArgs>(Action<object, TEventArgs> listener) where TEventArgs : EventArgs
{
if (listener == null) throw new ArgumentNullException(nameof(listener));
var type = typeof(Action<object, TEventArgs>);
_dicDelegates.AddOrUpdate(type,
_ => listener,
(_, existing) => Delegate.Combine(existing, listener));
}
public void RemoveListener<TEventArgs>(Action<object, TEventArgs> listener) where TEventArgs : EventArgs
{
if (listener == null) throw new ArgumentNullException(nameof(listener));
var type = typeof(Action<object, TEventArgs>);
if (_dicDelegates.TryGetValue(type, out var existing))
{
var updated = Delegate.Remove(existing, listener);
if (updated == null)
_dicDelegates.TryRemove(type, out _);
else
_dicDelegates.TryUpdate(type, updated, existing);
}
}
public void Dispatch<TEventArgs>(object sender, TEventArgs eventArgs) where TEventArgs : EventArgs
{
if (sender == null) throw new ArgumentNullException(nameof(sender));
if (eventArgs == null) throw new ArgumentNullException(nameof(eventArgs));
var type = typeof(Action<object, TEventArgs>);
if (_dicDelegates.TryGetValue(type, out var existingDelegate))
{
// Invoke each handler individually so one handler's exception
// doesn't prevent others from being called.
foreach (var handler in existingDelegate.GetInvocationList())
{
try
{
((Action<object, TEventArgs>)handler).Invoke(sender, eventArgs);
}
catch (Exception e)
{
GeneralTracer.Error("EventManager.Dispatch handler threw an exception.", e);
}
}
}
}
public void Clear() => _dicDelegates.Clear();
public void Dispose()
{
if (!_disposed)
{
_dicDelegates.Clear();
_disposed = true;
}
}
}
}