Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/WeakEvent.Tests/WeakEventLockingTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Xunit.Abstractions;

namespace ByteAether.WeakEvent.Tests;

public class WeakEventLockingTests(ITestOutputHelper output)
{
private readonly ITestOutputHelper _output = output;
Expand All @@ -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);
}

}
142 changes: 95 additions & 47 deletions src/WeakEvent/WeakEventCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,25 @@

internal sealed class WeakEventCore
{
private readonly List<WeakEventHandler> _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++;
}
}

Check notice

Code scanning / CodeQL

Missed opportunity to use Where Note

This foreach loop
implicitly filters its target sequence
- consider filtering the sequence explicitly using '.Where(...)'.

return count;
}
}

Expand All @@ -32,19 +35,20 @@
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);
}
}

Expand All @@ -55,18 +59,41 @@
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;
}
}

Expand All @@ -75,38 +102,59 @@
CancellationToken cancellationToken = default
)
{
List<WeakEventHandler> 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];
}

Check notice

Code scanning / CodeQL

Missed opportunity to use Where Note

This foreach loop
implicitly filters its target sequence
- consider filtering the sequence explicitly using '.Where(...)'.
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;
}
}
Comment thread
Seramis marked this conversation as resolved.
Dismissed

if (index < liveHandlers.Length)
{
Array.Resize(ref liveHandlers, index);
}

lock (_sync)
{
if (ReferenceEquals(_handlers, handlers))
{
Volatile.Write(ref _handlers, liveHandlers);
}
}

return liveHandlers;
}
}