diff --git a/PluralKit.Core/Utils/HandlerQueue.cs b/PluralKit.Core/Utils/HandlerQueue.cs index b8347bbb..9d261c0a 100644 --- a/PluralKit.Core/Utils/HandlerQueue.cs +++ b/PluralKit.Core/Utils/HandlerQueue.cs @@ -12,27 +12,18 @@ namespace PluralKit.Core private long _seq; private readonly ConcurrentDictionary _handlers = new ConcurrentDictionary(); - public HandlerEntry Add(Func> handler) - { - var entry = new HandlerEntry {Handler = handler}; - - _handlers[Interlocked.Increment(ref _seq)] = entry; - return entry; - } - public async Task WaitFor(Func predicate, Duration? timeout = null, CancellationToken ct = default) { var timeoutTask = Task.Delay(timeout?.ToTimeSpan() ?? TimeSpan.FromMilliseconds(-1), ct); var tcs = new TaskCompletionSource(); - Task Handler(T e) + ValueTask Handler(T e) { - var matches = predicate(e); - if (matches) tcs.SetResult(e); - return Task.FromResult(matches); + tcs.SetResult(e); + return default; } - var entry = new HandlerEntry {Handler = Handler}; + var entry = new HandlerEntry {Predicate = predicate, Handler = Handler}; _handlers[Interlocked.Increment(ref _seq)] = entry; // Wait for either the event task or the timeout task @@ -63,8 +54,9 @@ namespace PluralKit.Core foreach (var (_, entry) in _handlers) { if (entry.Expiry < now) entry.Alive = false; - else if (entry.Alive && await entry.Handler(evt)) + else if (entry.Alive && entry.Predicate(evt)) { + await entry.Handler(evt); entry.Alive = false; return true; } @@ -75,7 +67,8 @@ namespace PluralKit.Core public class HandlerEntry { - internal Func> Handler; + internal Func Handler; + internal Func Predicate; internal bool Alive = true; internal Instant Expiry = SystemClock.Instance.GetCurrentInstant() + Duration.FromMinutes(30);