|
2 | 2 | // This software is distributed under the MIT license and its code is open-source and free for use, modification, and distribution. |
3 | 3 | // </copyright> |
4 | 4 |
|
5 | | -using System.Collections.Concurrent; |
6 | 5 | using ZirconNet.Core.Extensions; |
7 | 6 |
|
8 | 7 | namespace ZirconNet.Core.Events; |
9 | 8 |
|
10 | 9 | public abstract class WeakEventBase |
11 | 10 | { |
12 | | - private readonly ConcurrentDictionary<Type, List<Delegate>> _eventRegistrations = new(); |
| 11 | + private readonly List<(Type, Delegate)> _eventRegistrations = new(); |
| 12 | + private readonly object _lock = new(); |
13 | 13 |
|
14 | 14 | protected virtual Subscription SubscribeInternal<T>(T action) |
15 | 15 | where T : Delegate |
16 | 16 | { |
17 | | - if (action is null) |
| 17 | + lock (_lock) |
18 | 18 | { |
19 | | - throw new ArgumentNullException(nameof(action)); |
20 | | - } |
| 19 | + if (action is null) |
| 20 | + { |
| 21 | + throw new ArgumentNullException(nameof(action)); |
| 22 | + } |
21 | 23 |
|
22 | | - _eventRegistrations.AddOrUpdate(typeof(T), new List<Delegate> { action }, (key, value) => |
23 | | - { |
24 | | - value.Add(action); |
25 | | - return value; |
26 | | - }); |
| 24 | + _eventRegistrations.Add((typeof(T), action)); |
27 | 25 |
|
28 | | - return new Subscription(() => _eventRegistrations.AddOrUpdate(typeof(T), new List<Delegate>(), (key, value) => |
29 | | - { |
30 | | - value.Remove(action); |
31 | | - return value; |
32 | | - })); |
| 26 | + return new Subscription(() => |
| 27 | + { |
| 28 | + lock (_lock) |
| 29 | + { |
| 30 | + _eventRegistrations.Remove((typeof(T), action)); |
| 31 | + } |
| 32 | + }); |
| 33 | + } |
33 | 34 | } |
34 | 35 |
|
35 | 36 | protected virtual void PublishInternal<T>(T? data) |
36 | 37 | { |
37 | 38 | Task.Run(() => |
38 | 39 | { |
39 | | - if (_eventRegistrations.TryGetValue(typeof(T), out var actions)) |
| 40 | + lock (_lock) |
40 | 41 | { |
41 | | - foreach (var action in actions) |
| 42 | + foreach (var eventRegistration in _eventRegistrations) |
42 | 43 | { |
43 | | - ((Action<T?>)action)(data); |
| 44 | + if (eventRegistration.Item2 is Action<T?> action) |
| 45 | + { |
| 46 | + action(data); |
| 47 | + } |
| 48 | + |
| 49 | + if (eventRegistration.Item2 is Func<T?> func) |
| 50 | + { |
| 51 | + func(); |
| 52 | + } |
44 | 53 | } |
45 | 54 | } |
46 | 55 | }).Forget(); |
|
0 commit comments