| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Threading; |
| | | 4 | | using System.Threading.Tasks; |
| | | 5 | | |
| | | 6 | | public sealed class SingleFactoryCaller<T> where T : class |
| | | 7 | | { |
| | 29 | 8 | | private readonly Dictionary<string, Lazy<Task<T>>> _pending = |
| | 29 | 9 | | new Dictionary<string, Lazy<Task<T>>>(); |
| | | 10 | | |
| | 29 | 11 | | private readonly object _gate = new object(); |
| | | 12 | | |
| | | 13 | | // cancellationToken is not applied: one waiter must not cancel the shared factory. |
| | | 14 | | public async Task<T> GetOrAddAsync(string key, Func<Task<T>> valueFactory, CancellationToken cancellationToken = def |
| | | 15 | | { |
| | 178 | 16 | | if (string.IsNullOrEmpty(key)) |
| | 4 | 17 | | throw new ArgumentException("Key cannot be null or empty.", nameof(key)); |
| | 174 | 18 | | if (valueFactory == null) |
| | 2 | 19 | | throw new ArgumentNullException(nameof(valueFactory)); |
| | | 20 | | |
| | | 21 | | Lazy<Task<T>> lazy; |
| | 172 | 22 | | lock (_gate) |
| | | 23 | | { |
| | 172 | 24 | | if (!_pending.TryGetValue(key, out lazy)) |
| | | 25 | | { |
| | 118 | 26 | | lazy = new Lazy<Task<T>>(() => Invoke(valueFactory), LazyThreadSafetyMode.ExecutionAndPublication); |
| | 59 | 27 | | _pending.Add(key, lazy); |
| | | 28 | | } |
| | 172 | 29 | | } |
| | | 30 | | |
| | | 31 | | try |
| | | 32 | | { |
| | 172 | 33 | | return await lazy.Value.ConfigureAwait(false); |
| | | 34 | | } |
| | | 35 | | finally |
| | | 36 | | { |
| | 172 | 37 | | lock (_gate) |
| | | 38 | | { |
| | | 39 | | // A finishing caller must leave a newer entry alone. |
| | 172 | 40 | | if (_pending.TryGetValue(key, out var current) && ReferenceEquals(current, lazy)) |
| | 59 | 41 | | _pending.Remove(key); |
| | 172 | 42 | | } |
| | | 43 | | } |
| | 130 | 44 | | } |
| | | 45 | | |
| | | 46 | | private static async Task<T> Invoke(Func<Task<T>> valueFactory) |
| | | 47 | | { |
| | 59 | 48 | | var task = valueFactory() ?? throw new InvalidOperationException("Value factory returned null task."); |
| | 56 | 49 | | return await task.ConfigureAwait(false); |
| | 49 | 50 | | } |
| | | 51 | | } |