| | 1 | | using System; |
| | 2 | | using System.Collections.Concurrent; |
| | 3 | | using System.Runtime.CompilerServices; |
| | 4 | | using System.Threading; |
| | 5 | | using System.Threading.Tasks; |
| | 6 | | using Amusoft.Toolkit.Threading.Compat; |
| | 7 | | using Amusoft.Toolkit.Threading.Exceptions; |
| | 8 | |
|
| | 9 | | namespace Amusoft.Toolkit.Threading; |
| | 10 | |
|
| | 11 | | /// <summary> |
| | 12 | | /// Debouncing API |
| | 13 | | /// </summary> |
| | 14 | | public class Debouncer |
| | 15 | | { |
| 1 | 16 | | private static readonly ConcurrentDictionary<LoaderIdentity, DebounceStack> Stacks = new(new IdentityComparer()); |
| | 17 | |
|
| 1 | 18 | | private static readonly ConditionalWeakTable<DebounceStack, LoaderIdentity> IdOfStack = new(); |
| | 19 | |
|
| | 20 | | /// <summary> |
| | 21 | | /// ensures that the last call with a given identity will provide the result for all awaiting tasks |
| | 22 | | /// </summary> |
| | 23 | | /// <typeparam name="T"></typeparam> |
| | 24 | | /// <returns></returns> |
| | 25 | | public static async Task<T> FromStackAsync<T>(Func<CancellationToken, Task<T>> expression, LoaderIdentity identity) |
| | 26 | | { |
| 6 | 27 | | var current = Stacks.GetOrAdd(identity, |
| 6 | 28 | | loaderIdentity => |
| 6 | 29 | | { |
| 3 | 30 | | var newStack = new DebounceStack<T>(); |
| 3 | 31 | | newStack.Task.ContinueWith(_ => |
| 3 | 32 | | { |
| 3 | 33 | | if (Stacks.TryRemove(loaderIdentity, out var prevStack)) |
| 3 | 34 | | IdOfStack.Remove(prevStack); |
| 3 | 35 | | } |
| 3 | 36 | | ); |
| 3 | 37 | | IdOfStack.Add(newStack, loaderIdentity); |
| 3 | 38 | | return newStack; |
| 6 | 39 | | }); |
| | 40 | |
|
| 6 | 41 | | if (current is not DebounceStack<T> stack) |
| 1 | 42 | | throw new TypeMismatchException(current.GetType(), typeof(DebounceStack<T>), identity); |
| | 43 | |
|
| 5 | 44 | | stack.CancelAndUpdate(expression); |
| | 45 | |
|
| 5 | 46 | | return await stack.Task; |
| 5 | 47 | | } |
| | 48 | | } |