diff --git a/src/Primitives.Core.Shared/Internal/CancellationRaceHelper.cs b/src/Primitives.Core.Shared/Internal/CancellationRaceHelper.cs new file mode 100644 index 00000000..19fa1544 --- /dev/null +++ b/src/Primitives.Core.Shared/Internal/CancellationRaceHelper.cs @@ -0,0 +1,31 @@ +// Copyright (c) 2019-2026 ReactiveUI Association Incorporated. All rights reserved. +// ReactiveUI Association Incorporated licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +#if PRIMITIVES_CORE +namespace ReactiveUI.Primitives.Core.Internal; +#elif REACTIVE_SHIM +namespace ReactiveUI.Primitives.Reactive.Internal; +#else +namespace ReactiveUI.Primitives.Internal; +#endif + +/// Synchronous cancellation helpers tolerant of concurrent source disposal. +internal static class CancellationRaceHelper +{ + /// Cancels , swallowing when another path disposed it first. + /// The cancellation token source to cancel. + /// when cancellation completed; when was already disposed. + internal static bool TryCancel(CancellationTokenSource cts) + { + try + { + cts.Cancel(); + return true; + } + catch (ObjectDisposedException) + { + return false; + } + } +} diff --git a/src/Primitives.Shared/Advanced/AsyncSubscriptionLifetime.cs b/src/Primitives.Shared/Advanced/AsyncSubscriptionLifetime.cs index 3e169c0b..dcf0915d 100644 --- a/src/Primitives.Shared/Advanced/AsyncSubscriptionLifetime.cs +++ b/src/Primitives.Shared/Advanced/AsyncSubscriptionLifetime.cs @@ -3,10 +3,13 @@ // See the LICENSE file in the project root for full license information. using System.Runtime.CompilerServices; - #if REACTIVE_SHIM +using ReactiveUI.Primitives.Reactive.Internal; + namespace ReactiveUI.Primitives.Reactive.Advanced; #else +using ReactiveUI.Primitives.Internal; + namespace ReactiveUI.Primitives.Advanced; #endif @@ -66,7 +69,7 @@ public void Dispose() } Volatile.Write(ref _canceled, 1); - CancelIgnoringDisposed(_cts); + _ = CancellationRaceHelper.TryCancel(_cts); _subscription.Dispose(); _cts.Dispose(); } @@ -88,19 +91,4 @@ internal bool TryComplete() _cts.Dispose(); return true; } - - /// Cancels the source while tolerating a concurrent completion disposing it first. - /// The cancellation source to cancel. - [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] - private static void CancelIgnoringDisposed(CancellationTokenSource cts) - { - try - { - cts.Cancel(); - } - catch (ObjectDisposedException) - { - // Concurrent completion does not prevent subscription disposal. - } - } } diff --git a/src/Primitives.Shared/Signals/Signal{FromTask}.cs b/src/Primitives.Shared/Signals/Signal{FromTask}.cs index 732118c9..e8bdd143 100644 --- a/src/Primitives.Shared/Signals/Signal{FromTask}.cs +++ b/src/Primitives.Shared/Signals/Signal{FromTask}.cs @@ -3,10 +3,13 @@ // See the LICENSE file in the project root for full license information. using System.Runtime.CompilerServices; - #if REACTIVE_SHIM +using ReactiveUI.Primitives.Reactive.Internal; + namespace ReactiveUI.Primitives.Reactive.Signals; #else +using ReactiveUI.Primitives.Internal; + namespace ReactiveUI.Primitives.Signals; #endif @@ -86,7 +89,7 @@ internal static ActionDisposable CancelOnDispose(TaskStopGate gate, Cancellation return; } - Cancel(source); + _ = CancellationRaceHelper.TryCancel(source); }); /// Delivers task completion only if the subscription has not claimed disposal. @@ -220,20 +223,6 @@ private static bool TryEmitSynchronously( return true; } - /// Cancels the source, tolerating a source another completion path disposed. - /// The cancellation source to cancel. - private static void Cancel(CancellationTokenSource source) - { - try - { - source.Cancel(); - } - catch (ObjectDisposedException) - { - // Cancellation remains harmless after task completion. - } - } - /// Claims completion before notifying the observer, excluding disposed subscriptions. internal sealed class TaskStopGate { @@ -332,7 +321,7 @@ public void Dispose() return; } - Cancel(SourceCore); + _ = CancellationRaceHelper.TryCancel(SourceCore); SourceCore.Dispose(); } diff --git a/src/Primitives.Shared/Signals/TaskSignal{T}.cs b/src/Primitives.Shared/Signals/TaskSignal{T}.cs index 1f3da471..1e416057 100644 --- a/src/Primitives.Shared/Signals/TaskSignal{T}.cs +++ b/src/Primitives.Shared/Signals/TaskSignal{T}.cs @@ -6,10 +6,12 @@ #if REACTIVE_SHIM using ReactiveUI.Primitives.Reactive.Advanced; +using ReactiveUI.Primitives.Reactive.Internal; namespace ReactiveUI.Primitives.Reactive.Signals; #else using ReactiveUI.Primitives.Advanced; +using ReactiveUI.Primitives.Internal; namespace ReactiveUI.Primitives.Signals; #endif @@ -95,15 +97,7 @@ private void Dispose(bool disposing) return; } - try - { - CancellationTokenSource.Cancel(); - } - catch (ObjectDisposedException) - { - // Cancellation remains harmless after task completion. - } - + _ = CancellationRaceHelper.TryCancel(CancellationTokenSource); _cleanUp.Dispose(); CancellationTokenSource.Dispose(); } diff --git a/src/ReactiveUI.Primitives.Async.Core/ConcurrencyRaceHelpers.cs b/src/ReactiveUI.Primitives.Async.Core/ConcurrencyRaceHelpers.cs index 56a27e57..7a140a16 100644 --- a/src/ReactiveUI.Primitives.Async.Core/ConcurrencyRaceHelpers.cs +++ b/src/ReactiveUI.Primitives.Async.Core/ConcurrencyRaceHelpers.cs @@ -2,9 +2,12 @@ // ReactiveUI Association Incorporated licenses this file to you under the MIT license. // See the LICENSE file in the project root for full license information. +using System.Runtime.CompilerServices; +using ReactiveUI.Primitives.Async.Internal; + namespace ReactiveUI.Primitives.Internal; -/// Atomic ownership claims and cancellation tolerant of prior disposal. +/// Atomic ownership claims, gate teardown, and cancellation tolerant of prior disposal. internal static class ConcurrencyRaceHelpers { /// Atomically transitions from to . @@ -14,6 +17,7 @@ internal static class ConcurrencyRaceHelpers /// /// when this caller won the claim; when another caller held it. /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool TryClaim(ref int state, int openSentinel, int claimedSentinel) => Interlocked.CompareExchange(ref state, claimedSentinel, openSentinel) == openSentinel; @@ -35,4 +39,53 @@ internal static async ValueTask TryCancelAsync(CancellationTokenSource cts return false; } } + + /// Executes , swallowing and raised during concurrent teardown. + /// The caller state type. + /// The state forwarded to . + /// The asynchronous teardown work. + /// + /// when completed normally; when + /// cancellation or prior disposal interrupted it. + /// + internal static async ValueTask IgnoreCanceledOrDisposedAsync( + TState state, + Func action) + { + try + { + await action(state).ConfigureAwait(false); + return true; + } + catch (OperationCanceledException) + { + return false; + } + catch (ObjectDisposedException) + { + return false; + } + } + + /// Enters and executes , ignoring cancellation or disposal races. + /// The caller state type. + /// The serialization gate to enter. + /// The state forwarded to . + /// The mutation to run while holding . + /// The disposal token guarding the gate wait. + /// A task representing the gated teardown operation. + internal static async ValueTask RunUnderGateIgnoringTeardownAsync( + AsyncFlowGate gate, + TState state, + Action action, + CancellationToken cancellationToken) => + _ = await IgnoreCanceledOrDisposedAsync( + (Gate: gate, Token: cancellationToken, State: state, Action: action), + static async s => + { + using (await s.Gate.EnterAsync(s.Token).ConfigureAwait(false)) + { + s.Action(s.State); + } + }).ConfigureAwait(false); } diff --git a/src/ReactiveUI.Primitives.Async.Core/Signals/Base/ReplayLatestSignalAsyncStateObserverLease{T}.cs b/src/ReactiveUI.Primitives.Async.Core/Signals/Base/ReplayLatestSignalAsyncStateObserverLease{T}.cs index fa408ea9..c7912c35 100644 --- a/src/ReactiveUI.Primitives.Async.Core/Signals/Base/ReplayLatestSignalAsyncStateObserverLease{T}.cs +++ b/src/ReactiveUI.Primitives.Async.Core/Signals/Base/ReplayLatestSignalAsyncStateObserverLease{T}.cs @@ -2,6 +2,9 @@ // ReactiveUI Association Incorporated licenses this file to you under the MIT license. // See the LICENSE file in the project root for full license information. +using System.Runtime.CompilerServices; +using ReactiveUI.Primitives.Internal; + namespace ReactiveUI.Primitives.Async.Signals; /// Subscription handle that removes an observer from a replay signal when disposed. @@ -16,34 +19,17 @@ internal sealed class ReplayLatestSignalAsyncStateObserverLease( private int _disposed; /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask DisposeAsync() => - Interlocked.Exchange(ref _disposed, 1) != 0 + Interlocked.Exchange(ref _disposed, 1) != 0 || state.IsDisposed ? default - : RemoveObserverAsync(); - - /// Removes the observer from the replay signal under the serialization gate. - /// A task that represents the asynchronous removal operation. - private async ValueTask RemoveObserverAsync() - { - if (state.IsDisposed) - { - return; - } + : ConcurrencyRaceHelpers.RunUnderGateIgnoringTeardownAsync( + state.Gate, + this, + static self => self.RemoveCore(), + state.DisposedCancellationToken); - try - { - using (await state.Gate.EnterAsync(state.DisposedCancellationToken).ConfigureAwait(false)) - { - state.Observers = state.Observers.Remove(observer); - } - } - catch (OperationCanceledException) - { - // Unsubscription is harmless after signal disposal. - } - catch (ObjectDisposedException) - { - // Unsubscription is harmless after signal disposal. - } - } + /// Removes the observer while holding the state gate. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void RemoveCore() => state.Observers = state.Observers.Remove(observer); } diff --git a/src/ReactiveUI.Primitives.Async.Core/Signals/Base/StatelessReplayLatestSignalAsyncStateObserverLease{T}.cs b/src/ReactiveUI.Primitives.Async.Core/Signals/Base/StatelessReplayLatestSignalAsyncStateObserverLease{T}.cs index 16301b09..cf4dd489 100644 --- a/src/ReactiveUI.Primitives.Async.Core/Signals/Base/StatelessReplayLatestSignalAsyncStateObserverLease{T}.cs +++ b/src/ReactiveUI.Primitives.Async.Core/Signals/Base/StatelessReplayLatestSignalAsyncStateObserverLease{T}.cs @@ -2,6 +2,9 @@ // ReactiveUI Association Incorporated licenses this file to you under the MIT license. // See the LICENSE file in the project root for full license information. +using System.Runtime.CompilerServices; +using ReactiveUI.Primitives.Internal; + namespace ReactiveUI.Primitives.Async.Signals; /// Subscription handle that removes an observer from a stateless replay signal when disposed. @@ -16,38 +19,23 @@ internal sealed class StatelessReplayLatestSignalAsyncStateObserverLease( private int _disposed; /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask DisposeAsync() => - Interlocked.Exchange(ref _disposed, 1) != 0 + Interlocked.Exchange(ref _disposed, 1) != 0 || state.IsDisposed ? default - : RemoveObserverAndResetAsync(); + : ConcurrencyRaceHelpers.RunUnderGateIgnoringTeardownAsync( + state.Gate, + this, + static self => self.RemoveAndResetCore(), + state.DisposedCancellationToken); /// Removes the observer and restores the initial value when the last observer leaves. - /// A task that represents the asynchronous removal operation. - private async ValueTask RemoveObserverAndResetAsync() + private void RemoveAndResetCore() { - if (state.IsDisposed) - { - return; - } - - try - { - using (await state.Gate.EnterAsync(state.DisposedCancellationToken).ConfigureAwait(false)) - { - state.Observers = state.Observers.Remove(observer); - if (state.Observers.IsEmpty) - { - state.Value = state.InitialValue; - } - } - } - catch (OperationCanceledException) - { - // Unsubscription is harmless after signal disposal. - } - catch (ObjectDisposedException) + state.Observers = state.Observers.Remove(observer); + if (state.Observers.IsEmpty) { - // Unsubscription is harmless after signal disposal. + state.Value = state.InitialValue; } } } diff --git a/src/tests/ReactiveUI.Primitives.Async.Tests/ConcurrencyRaceHelpersTests.cs b/src/tests/ReactiveUI.Primitives.Async.Tests/ConcurrencyRaceHelpersTests.cs new file mode 100644 index 00000000..5d23460a --- /dev/null +++ b/src/tests/ReactiveUI.Primitives.Async.Tests/ConcurrencyRaceHelpersTests.cs @@ -0,0 +1,108 @@ +// Copyright (c) 2019-2026 ReactiveUI Association Incorporated. All rights reserved. +// ReactiveUI Association Incorporated licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using System.Runtime.CompilerServices; +using ReactiveUI.Primitives.Async.Internal; +using ReactiveUI.Primitives.Internal; + +namespace ReactiveUI.Primitives.Async.Tests; + +/// Tests for . +public sealed class ConcurrencyRaceHelpersTests +{ + /// Verifies atomic state claiming succeeds once and rejects competing callers. + /// A task representing the asynchronous test. + [Test] + public async Task TryClaim_TransitionsOnceAndRejectsSecondClaim() + { + var state = 0; + await Assert.That(ConcurrencyRaceHelpers.TryClaim(ref state, 0, 1)).IsTrue(); + await Assert.That(state).IsEqualTo(1); + await Assert.That(ConcurrencyRaceHelpers.TryClaim(ref state, 0, 1)).IsFalse(); + } + + /// Verifies cancels active sources and swallows disposed ones. + /// A task representing the asynchronous test. + [Test] + public async Task TryCancelAsync_ActiveAndDisposedSources_ReturnsExpectedStatus() + { + using CancellationTokenSource active = new(); + await Assert.That(await ConcurrencyRaceHelpers.TryCancelAsync(active)).IsTrue(); + await Assert.That(active.IsCancellationRequested).IsTrue(); + + CancellationTokenSource disposed = new(); + disposed.Dispose(); + await Assert.That(await ConcurrencyRaceHelpers.TryCancelAsync(disposed)).IsFalse(); + } + + /// Verifies swallows cancellation and disposal while propagating unexpected failures. + /// A task representing the asynchronous test. + [Test] + public async Task IgnoreCanceledOrDisposedAsync_HandlesSuccessCancellationDisposalAndOtherErrors() + { + StrongBox calls = new(); + var completed = await ConcurrencyRaceHelpers.IgnoreCanceledOrDisposedAsync( + calls, + static box => + { + box.Value++; + return default; + }); + await Assert.That(completed).IsTrue(); + await Assert.That(calls.Value).IsEqualTo(1); + + var canceled = await ConcurrencyRaceHelpers.IgnoreCanceledOrDisposedAsync( + 0, + static _ => ValueTask.FromException(new OperationCanceledException())); + await Assert.That(canceled).IsFalse(); + + var taskCanceled = await ConcurrencyRaceHelpers.IgnoreCanceledOrDisposedAsync( + 0, + static _ => ValueTask.FromException(new TaskCanceledException())); + await Assert.That(taskCanceled).IsFalse(); + + var disposed = await ConcurrencyRaceHelpers.IgnoreCanceledOrDisposedAsync( + 0, + static _ => ValueTask.FromException(new ObjectDisposedException("disposed"))); + await Assert.That(disposed).IsFalse(); + + await Assert.That(static async () => await ConcurrencyRaceHelpers.IgnoreCanceledOrDisposedAsync( + 0, + static _ => ValueTask.FromException(new InvalidOperationException("unexpected")))) + .ThrowsExactly(); + } + + /// Verifies runs under an open gate and tolerates cancelled waits. + /// A task representing the asynchronous test. + [Test] + public async Task RunUnderGateIgnoringTeardownAsync_RunsWhenOpenAndSwallowsCancelledWait() + { + AsyncFlowGate gate = new(); + StrongBox counter = new(); + await ConcurrencyRaceHelpers.RunUnderGateIgnoringTeardownAsync( + gate, + counter, + static box => box.Value++, + CancellationToken.None); + await Assert.That(counter.Value).IsEqualTo(1); + + TaskCompletionSource releaseGate = new(TaskCreationOptions.RunContinuationsAsynchronously); + using CancellationTokenSource cts = new(); + try + { + _ = AsyncFlowGateHolder.HoldAsync(gate, releaseGate.Task); + await cts.CancelAsync(); + await ConcurrencyRaceHelpers.RunUnderGateIgnoringTeardownAsync( + gate, + counter, + static box => box.Value++, + cts.Token); + await Assert.That(counter.Value).IsEqualTo(1); + } + finally + { + _ = releaseGate.TrySetResult(); + } + } +} diff --git a/src/tests/ReactiveUI.Primitives.Tests/CancellationRaceHelperTests.cs b/src/tests/ReactiveUI.Primitives.Tests/CancellationRaceHelperTests.cs new file mode 100644 index 00000000..51e3b553 --- /dev/null +++ b/src/tests/ReactiveUI.Primitives.Tests/CancellationRaceHelperTests.cs @@ -0,0 +1,34 @@ +// Copyright (c) 2019-2026 ReactiveUI Association Incorporated. All rights reserved. +// ReactiveUI Association Incorporated licenses this file to you under the MIT license. +// See the LICENSE file in the project root for full license information. + +using ReactiveUI.Primitives.Internal; +using CoreCancellationRaceHelper = ReactiveUI.Primitives.Core.Internal.CancellationRaceHelper; + +namespace ReactiveUI.Primitives.Tests; + +/// Tests for . +public sealed class CancellationRaceHelperTests +{ + /// Verifies cancels active sources and swallows disposed sources. + /// A task representing the asynchronous test. + [Test] + public async Task TryCancel_ActiveAndDisposedSources_ReturnsExpectedStatus() + { + using CancellationTokenSource active = new(); + await Assert.That(CancellationRaceHelper.TryCancel(active)).IsTrue(); + await Assert.That(active.IsCancellationRequested).IsTrue(); + + CancellationTokenSource disposed = new(); + disposed.Dispose(); + await Assert.That(CancellationRaceHelper.TryCancel(disposed)).IsFalse(); + + using CancellationTokenSource coreActive = new(); + await Assert.That(CoreCancellationRaceHelper.TryCancel(coreActive)).IsTrue(); + await Assert.That(coreActive.IsCancellationRequested).IsTrue(); + + CancellationTokenSource coreDisposed = new(); + coreDisposed.Dispose(); + await Assert.That(CoreCancellationRaceHelper.TryCancel(coreDisposed)).IsFalse(); + } +}