-
Notifications
You must be signed in to change notification settings - Fork 8
/
ScarceEventSource.cs
68 lines (58 loc) · 1.83 KB
/
ScarceEventSource.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
namespace Events;
public class ScarceEventSource
{
// One dictionary shared by all instances of this class,
// tracking all handlers for all events.
// Beware of memory leaks - this code is for illustration only.
private static readonly
Dictionary<(ScarceEventSource, object), EventHandler> _eventHandlers
= new();
// Objects used as keys to identify particular events in the dictionary.
private static readonly object EventOneId = new();
private static readonly object EventTwoId = new();
public event EventHandler EventOne
{
add => AddEvent(EventOneId, value);
remove => RemoveEvent(EventOneId, value);
}
public event EventHandler EventTwo
{
add => AddEvent(EventTwoId, value);
remove => RemoveEvent(EventTwoId, value);
}
public void RaiseBoth()
{
RaiseEvent(EventOneId, EventArgs.Empty);
RaiseEvent(EventTwoId, EventArgs.Empty);
}
private (ScarceEventSource, object) MakeKey(object eventId) => (this, eventId);
private void AddEvent(object eventId, EventHandler handler)
{
var key = MakeKey(eventId);
_eventHandlers.TryGetValue(key, out EventHandler? entry);
entry += handler;
_eventHandlers[key] = entry;
}
private void RemoveEvent(object eventId, EventHandler handler)
{
var key = MakeKey(eventId);
EventHandler? entry = _eventHandlers[key];
entry -= handler;
if (entry == null)
{
_eventHandlers.Remove(key);
}
else
{
_eventHandlers[key] = entry;
}
}
private void RaiseEvent(object eventId, EventArgs e)
{
var key = MakeKey(eventId);
if (_eventHandlers.TryGetValue(key, out EventHandler? handler))
{
handler(this, e);
}
}
}