-
Notifications
You must be signed in to change notification settings - Fork 0
/
Events.cs
64 lines (49 loc) · 1.36 KB
/
Events.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
using System.Diagnostics;
namespace Httpd;
public delegate Task AsyncEventHandler<in T>(T e) where T : AsyncEventArgs;
public class AsyncEventArgs
{
public bool Handled { get; set; }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public static AsyncEventArgs Empty => new();
}
public class AsyncEvent<T> where T : AsyncEventArgs
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly List<AsyncEventHandler<T>> _handlerList = new();
public AsyncEvent()
{
}
public void AddHandler(AsyncEventHandler<T> func)
{
lock (_handlerList)
_handlerList.Add(func);
}
public void RemoveHandler(AsyncEventHandler<T> func)
{
lock (_handlerList)
_handlerList.Remove(func);
}
public async Task InvokeAsync(T e)
{
AsyncEventHandler<T>[] handlers;
lock (_handlerList)
handlers = _handlerList.ToArray();
var exceptions = new List<Exception>();
foreach (var handler in handlers)
{
try
{
await handler(e);
if (e.Handled)
break;
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
if (exceptions.Count > 0)
throw new AggregateException(exceptions);
}
}