| | | 1 | | namespace NGql.Core.Features; |
| | | 2 | | |
| | | 3 | | internal sealed class MergeMemoScope |
| | | 4 | | { |
| | | 5 | | private long _version; |
| | | 6 | | |
| | 2256 | 7 | | internal long Version => Interlocked.Read(ref _version); |
| | | 8 | | |
| | 168 | 9 | | internal void Invalidate() => Interlocked.Increment(ref _version); |
| | | 10 | | } |
| | | 11 | | |
| | | 12 | | internal sealed class MergeMemoTracker |
| | | 13 | | { |
| | | 14 | | private MergeMemoScope? _primary; |
| | | 15 | | private object? _gate; |
| | | 16 | | private volatile List<WeakReference<MergeMemoScope>>? _others; |
| | | 17 | | |
| | | 18 | | internal void Attach(MergeMemoScope scope) |
| | | 19 | | { |
| | | 20 | | if (ReferenceEquals(Volatile.Read(ref _primary), scope)) return; |
| | | 21 | | var primary = Interlocked.CompareExchange(ref _primary, scope, null); |
| | | 22 | | if (primary is null || ReferenceEquals(primary, scope)) return; |
| | | 23 | | lock (LazyInitializer.EnsureInitialized(ref _gate)) |
| | | 24 | | { |
| | | 25 | | _others ??= new(); |
| | | 26 | | for (var i = _others.Count - 1; i >= 0; i--) |
| | | 27 | | { |
| | | 28 | | if (!_others[i].TryGetTarget(out var target)) _others.RemoveAt(i); |
| | | 29 | | else if (ReferenceEquals(target, scope)) return; |
| | | 30 | | } |
| | | 31 | | _others.Add(new WeakReference<MergeMemoScope>(scope)); |
| | | 32 | | } |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | internal void Invalidate() |
| | | 36 | | { |
| | | 37 | | Volatile.Read(ref _primary)?.Invalidate(); |
| | | 38 | | if (_others is null) return; |
| | | 39 | | lock (_gate!) |
| | | 40 | | { |
| | | 41 | | for (var i = _others.Count - 1; i >= 0; i--) |
| | | 42 | | { |
| | | 43 | | if (_others[i].TryGetTarget(out var scope)) scope.Invalidate(); |
| | | 44 | | else _others.RemoveAt(i); |
| | | 45 | | } |
| | | 46 | | } |
| | | 47 | | } |
| | | 48 | | } |