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
31 changes: 31 additions & 0 deletions src/Primitives.Core.Shared/Internal/CancellationRaceHelper.cs
Original file line number Diff line number Diff line change
@@ -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

/// <summary>Synchronous cancellation helpers tolerant of concurrent source disposal.</summary>
internal static class CancellationRaceHelper
{
/// <summary>Cancels <paramref name="cts"/>, swallowing <see cref="ObjectDisposedException"/> when another path disposed it first.</summary>
/// <param name="cts">The cancellation token source to cancel.</param>
/// <returns><see langword="true"/> when cancellation completed; <see langword="false"/> when <paramref name="cts"/> was already disposed.</returns>
internal static bool TryCancel(CancellationTokenSource cts)
{
try
{
cts.Cancel();
return true;
}
catch (ObjectDisposedException)
{
return false;
}
}
}
22 changes: 5 additions & 17 deletions src/Primitives.Shared/Advanced/AsyncSubscriptionLifetime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -66,7 +69,7 @@ public void Dispose()
}

Volatile.Write(ref _canceled, 1);
CancelIgnoringDisposed(_cts);
_ = CancellationRaceHelper.TryCancel(_cts);
_subscription.Dispose();
_cts.Dispose();
}
Expand All @@ -88,19 +91,4 @@ internal bool TryComplete()
_cts.Dispose();
return true;
}

/// <summary>Cancels the source while tolerating a concurrent completion disposing it first.</summary>
/// <param name="cts">The cancellation source to cancel.</param>
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
private static void CancelIgnoringDisposed(CancellationTokenSource cts)
{
try
{
cts.Cancel();
}
catch (ObjectDisposedException)
{
// Concurrent completion does not prevent subscription disposal.
}
}
}
23 changes: 6 additions & 17 deletions src/Primitives.Shared/Signals/Signal{FromTask}.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -86,7 +89,7 @@ internal static ActionDisposable CancelOnDispose(TaskStopGate gate, Cancellation
return;
}

Cancel(source);
_ = CancellationRaceHelper.TryCancel(source);
});

/// <summary>Delivers task completion only if the subscription has not claimed disposal.</summary>
Expand Down Expand Up @@ -220,20 +223,6 @@ private static bool TryEmitSynchronously<TResult>(
return true;
}

/// <summary>Cancels the source, tolerating a source another completion path disposed.</summary>
/// <param name="source">The cancellation source to cancel.</param>
private static void Cancel(CancellationTokenSource source)
{
try
{
source.Cancel();
}
catch (ObjectDisposedException)
{
// Cancellation remains harmless after task completion.
}
}

/// <summary>Claims completion before notifying the observer, excluding disposed subscriptions.</summary>
internal sealed class TaskStopGate
{
Expand Down Expand Up @@ -332,7 +321,7 @@ public void Dispose()
return;
}

Cancel(SourceCore);
_ = CancellationRaceHelper.TryCancel(SourceCore);
SourceCore.Dispose();
}

Expand Down
12 changes: 3 additions & 9 deletions src/Primitives.Shared/Signals/TaskSignal{T}.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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();
}
Expand Down
55 changes: 54 additions & 1 deletion src/ReactiveUI.Primitives.Async.Core/ConcurrencyRaceHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/// <summary>Atomic ownership claims and cancellation tolerant of prior disposal.</summary>
/// <summary>Atomic ownership claims, gate teardown, and cancellation tolerant of prior disposal.</summary>
internal static class ConcurrencyRaceHelpers
{
/// <summary>Atomically transitions <paramref name="state"/> from <paramref name="openSentinel"/> to <paramref name="claimedSentinel"/>.</summary>
Expand All @@ -14,6 +17,7 @@ internal static class ConcurrencyRaceHelpers
/// <returns>
/// <see langword="true"/> when this caller won the claim; <see langword="false"/> when another caller held it.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool TryClaim(ref int state, int openSentinel, int claimedSentinel) =>
Interlocked.CompareExchange(ref state, claimedSentinel, openSentinel) == openSentinel;

Expand All @@ -35,4 +39,53 @@ internal static async ValueTask<bool> TryCancelAsync(CancellationTokenSource cts
return false;
}
}

/// <summary>Executes <paramref name="action"/>, swallowing <see cref="OperationCanceledException"/> and <see cref="ObjectDisposedException"/> raised during concurrent teardown.</summary>
/// <typeparam name="TState">The caller state type.</typeparam>
/// <param name="state">The state forwarded to <paramref name="action"/>.</param>
/// <param name="action">The asynchronous teardown work.</param>
/// <returns>
/// <see langword="true"/> when <paramref name="action"/> completed normally; <see langword="false"/> when
/// cancellation or prior disposal interrupted it.
/// </returns>
internal static async ValueTask<bool> IgnoreCanceledOrDisposedAsync<TState>(
TState state,
Func<TState, ValueTask> action)
{
try
{
await action(state).ConfigureAwait(false);
return true;
}
catch (OperationCanceledException)
{
return false;
}
catch (ObjectDisposedException)
{
return false;
}
}

/// <summary>Enters <paramref name="gate"/> and executes <paramref name="action"/>, ignoring cancellation or disposal races.</summary>
/// <typeparam name="TState">The caller state type.</typeparam>
/// <param name="gate">The serialization gate to enter.</param>
/// <param name="state">The state forwarded to <paramref name="action"/>.</param>
/// <param name="action">The mutation to run while holding <paramref name="gate"/>.</param>
/// <param name="cancellationToken">The disposal token guarding the gate wait.</param>
/// <returns>A task representing the gated teardown operation.</returns>
internal static async ValueTask RunUnderGateIgnoringTeardownAsync<TState>(
AsyncFlowGate gate,
TState state,
Action<TState> 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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/// <summary>Subscription handle that removes an observer from a replay signal when disposed.</summary>
Expand All @@ -16,34 +19,17 @@ internal sealed class ReplayLatestSignalAsyncStateObserverLease<T>(
private int _disposed;

/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ValueTask DisposeAsync() =>
Interlocked.Exchange(ref _disposed, 1) != 0
Interlocked.Exchange(ref _disposed, 1) != 0 || state.IsDisposed
? default
: RemoveObserverAsync();

/// <summary>Removes the observer from the replay signal under the serialization gate.</summary>
/// <returns>A task that represents the asynchronous removal operation.</returns>
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.
}
}
/// <summary>Removes the observer while holding the state gate.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void RemoveCore() => state.Observers = state.Observers.Remove(observer);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/// <summary>Subscription handle that removes an observer from a stateless replay signal when disposed.</summary>
Expand All @@ -16,38 +19,23 @@ internal sealed class StatelessReplayLatestSignalAsyncStateObserverLease<T>(
private int _disposed;

/// <inheritdoc/>
[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);

/// <summary>Removes the observer and restores the initial value when the last observer leaves.</summary>
/// <returns>A task that represents the asynchronous removal operation.</returns>
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;
}
}
}
Loading
Loading