diff --git a/src/WeakEvent.Tests/WeakEventLockingTests.cs b/src/WeakEvent.Tests/WeakEventLockingTests.cs index 38b43d2..fad1fcc 100644 --- a/src/WeakEvent.Tests/WeakEventLockingTests.cs +++ b/src/WeakEvent.Tests/WeakEventLockingTests.cs @@ -1,6 +1,7 @@ using Xunit.Abstractions; namespace ByteAether.WeakEvent.Tests; + public class WeakEventLockingTests(ITestOutputHelper output) { private readonly ITestOutputHelper _output = output; @@ -19,4 +20,36 @@ public async Task Handler_CanUnsubscribeItself() e.Subscribe(handler); await e.PublishAsync(); } + + [Fact] + public async Task SubscriptionChanges_DuringPublication_AreAppliedToNextPublication() + { + WeakEvent e = new(); + TaskCompletionSource entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + TaskCompletionSource release = new(TaskCreationOptions.RunContinuationsAsynchronously); + var callCount = 0; + + async Task firstHandler() + { + entered.TrySetResult(); + await release.Task; + callCount++; + } + + void secondHandler() => callCount++; + + e.Subscribe(firstHandler); + var firstPublication = e.PublishAsync(); + await entered.Task; + + e.Subscribe(secondHandler); + release.SetResult(); + await firstPublication; + + Assert.Equal(1, callCount); + + await e.PublishAsync(); + Assert.Equal(3, callCount); + } + } \ No newline at end of file diff --git a/src/WeakEvent/WeakEventCore.cs b/src/WeakEvent/WeakEventCore.cs index dba104d..963171e 100644 --- a/src/WeakEvent/WeakEventCore.cs +++ b/src/WeakEvent/WeakEventCore.cs @@ -2,22 +2,25 @@ namespace ByteAether.WeakEvent; internal sealed class WeakEventCore { - private readonly List _handlers = []; - private readonly ReaderWriterLockSlim _rwLock = new(); + private readonly object _sync = new(); + private WeakEventHandler[] _handlers = []; public int SubscriberCount { get { - _rwLock.EnterReadLock(); - try - { - return _handlers.Count(x => x.IsAlive); - } - finally + var handlers = Volatile.Read(ref _handlers); + var count = 0; + + foreach (var handler in handlers) { - _rwLock.ExitReadLock(); + if (handler.IsAlive) + { + count++; + } } + + return count; } } @@ -32,19 +35,20 @@ Func createHandler throw new ArgumentNullException(nameof(handler)); } - var handlers = handler - .GetInvocationList() - .Select(invocation => createHandler((TDelegate)invocation)) - .ToArray(); + var invocations = handler.GetInvocationList(); + var handlers = new WeakEventHandler[invocations.Length]; - _rwLock.EnterWriteLock(); - try + for (var i = 0; i < invocations.Length; i++) { - _handlers.AddRange(handlers); + handlers[i] = createHandler((TDelegate)invocations[i]); } - finally + + lock (_sync) { - _rwLock.ExitWriteLock(); + var combined = new WeakEventHandler[_handlers.Length + handlers.Length]; + _handlers.CopyTo(combined, 0); + handlers.CopyTo(combined, _handlers.Length); + Volatile.Write(ref _handlers, combined); } } @@ -55,18 +59,41 @@ public bool Unsubscribe(Delegate handler) throw new ArgumentNullException(nameof(handler)); } - var handlers = handler.GetInvocationList(); + var invocations = handler.GetInvocationList(); - _rwLock.EnterWriteLock(); - try + lock (_sync) { - return _handlers.RemoveAll( - weakHandler => handlers.Any(weakHandler.Matches) - ) > 0; - } - finally - { - _rwLock.ExitWriteLock(); + var handlers = _handlers; + var remaining = new WeakEventHandler[handlers.Length]; + var count = 0; + + foreach (var weakHandler in handlers) + { + var remove = false; + + foreach (var invocation in invocations) + { + if (weakHandler.Matches(invocation)) + { + remove = true; + break; + } + } + + if (!remove) + { + remaining[count++] = weakHandler; + } + } + + if (count == handlers.Length) + { + return false; + } + + Array.Resize(ref remaining, count); + Volatile.Write(ref _handlers, remaining); + return true; } } @@ -75,38 +102,59 @@ public async Task PublishAsync( CancellationToken cancellationToken = default ) { - List handlers; + cancellationToken.ThrowIfCancellationRequested(); - _rwLock.EnterUpgradeableReadLock(); + var handlers = GetLiveSnapshot(); - try + foreach (var handler in handlers) { cancellationToken.ThrowIfCancellationRequested(); + await handler.InvokeAsync(eventData, cancellationToken); + } + } + + private WeakEventHandler[] GetLiveSnapshot() + { + var handlers = Volatile.Read(ref _handlers); + var liveCount = 0; - if (_handlers.Any(x => !x.IsAlive)) + foreach (var handler in handlers) + { + if (handler.IsAlive) { - _rwLock.EnterWriteLock(); - try - { - _handlers.RemoveAll(x => !x.IsAlive); - } - finally - { - _rwLock.ExitWriteLock(); - } + liveCount++; } - - handlers = [.. _handlers]; } - finally + + if (liveCount == handlers.Length) { - _rwLock.ExitUpgradeableReadLock(); + return handlers; } + var liveHandlers = new WeakEventHandler[liveCount]; + var index = 0; + foreach (var handler in handlers) { - cancellationToken.ThrowIfCancellationRequested(); - await handler.InvokeAsync(eventData, cancellationToken); + if (handler.IsAlive) + { + liveHandlers[index++] = handler; + } + } + + if (index < liveHandlers.Length) + { + Array.Resize(ref liveHandlers, index); } + + lock (_sync) + { + if (ReferenceEquals(_handlers, handlers)) + { + Volatile.Write(ref _handlers, liveHandlers); + } + } + + return liveHandlers; } } \ No newline at end of file