Split HandlerQueue logic into Predicate/Handler
This commit is contained in:
		| @@ -12,27 +12,18 @@ namespace PluralKit.Core | ||||
|         private long _seq; | ||||
|         private readonly ConcurrentDictionary<long, HandlerEntry> _handlers = new ConcurrentDictionary<long, HandlerEntry>(); | ||||
|  | ||||
|         public HandlerEntry Add(Func<T, Task<bool>> handler) | ||||
|         { | ||||
|             var entry = new HandlerEntry {Handler = handler}; | ||||
|  | ||||
|             _handlers[Interlocked.Increment(ref _seq)] = entry; | ||||
|             return entry; | ||||
|         } | ||||
|  | ||||
|         public async Task<T> WaitFor(Func<T, bool> predicate, Duration? timeout = null, CancellationToken ct = default) | ||||
|         { | ||||
|             var timeoutTask = Task.Delay(timeout?.ToTimeSpan() ?? TimeSpan.FromMilliseconds(-1), ct); | ||||
|             var tcs = new TaskCompletionSource<T>(); | ||||
|  | ||||
|             Task<bool> 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<T, Task<bool>> Handler; | ||||
|             internal Func<T, ValueTask> Handler; | ||||
|             internal Func<T, bool> Predicate; | ||||
|             internal bool Alive = true; | ||||
|             internal Instant Expiry = SystemClock.Instance.GetCurrentInstant() + Duration.FromMinutes(30); | ||||
|  | ||||
|   | ||||
		Reference in New Issue
	
	Block a user