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
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,11 @@ private void EnsureCallbacksInitialized()
if (ChangeTokens[i].ActiveChangeCallbacks)
{
IDisposable disposable = ChangeTokens[i].RegisterChangeCallback(_onChangeDelegate, this);
if (_cancellationTokenSource.IsCancellationRequested)
{
disposable.Dispose();
break;
}
_disposables.Add(disposable);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,5 +148,66 @@ public async Task RegisteredCallbackGetsInvokedExactlyOnce_WhenMultipleConcurren
// Assert
Assert.Equal(1, count);
}

[Fact]
public void ShouldNotCollectDisposablesIfChangedTokenEncountered()
{
// Arrange
var firstCancellationTokenSource = new CancellationTokenSource();
var secondCancellationTokenSource = new CancellationTokenSource();
var thirdCancellationTokenSource = new CancellationTokenSource();
var count = 0;
var compositeChangeToken = new CompositeChangeToken(new List<IChangeToken> {
new ProxyCancellationChangeToken(firstCancellationTokenSource.Token, disposing: () => count++),
new ProxyCancellationChangeToken(secondCancellationTokenSource.Token, disposing: () => count++),
new ProxyCancellationChangeToken(thirdCancellationTokenSource.Token, disposing: () => count++) });

// Act
firstCancellationTokenSource.Cancel();
compositeChangeToken.RegisterChangeCallback(_ => { }, null);
secondCancellationTokenSource.Cancel();

// Assert
Assert.Equal(1, count);
}
}

internal class ProxyCancellationChangeToken : IChangeToken
{
private readonly CancellationChangeToken _cancellationChangeToken;
private readonly Action _disposing;

public ProxyCancellationChangeToken(CancellationToken cancellationToken, Action disposing)
{
_cancellationChangeToken = new CancellationChangeToken(cancellationToken);
_disposing = disposing;
}
public bool ActiveChangeCallbacks => _cancellationChangeToken.ActiveChangeCallbacks;

public bool HasChanged => _cancellationChangeToken.HasChanged;

public IDisposable RegisterChangeCallback(Action<object?> callback, object? state)
{
IDisposable registration = _cancellationChangeToken.RegisterChangeCallback(callback, state);
return new Registration(_disposing, registration);
}

private class Registration : IDisposable
{
private readonly Action _disposing;
private readonly IDisposable _registration;

public Registration(Action disposing, IDisposable registration)
{
_disposing = disposing;
_registration = registration;
}

public void Dispose()
{
_registration?.Dispose();
_disposing();
}
}
}
}