// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT License.
// See the LICENSE file in the project root for more information.
using System.Threading;
namespace System.Reactive.Disposables
{
///
/// Represents an Action-based disposable.
///
internal sealed class AnonymousDisposable : ICancelable
{
private volatile Action? _dispose;
///
/// Constructs a new disposable with the given action used for disposal.
///
/// Disposal action which will be run upon calling Dispose.
public AnonymousDisposable(Action dispose)
{
Diagnostics.Debug.Assert(dispose != null);
_dispose = dispose;
}
///
/// Gets a value that indicates whether the object is disposed.
///
public bool IsDisposed => _dispose == null;
///
/// Calls the disposal action if and only if the current instance hasn't been disposed yet.
///
public void Dispose()
{
Interlocked.Exchange(ref _dispose, null)?.Invoke();
}
}
///
/// Represents a Action-based disposable that can hold onto some state.
///
internal sealed class AnonymousDisposable : ICancelable
{
private TState _state;
private volatile Action? _dispose;
///
/// Constructs a new disposable with the given action used for disposal.
///
/// The state to be passed to the disposal action.
/// Disposal action which will be run upon calling Dispose.
public AnonymousDisposable(TState state, Action dispose)
{
Diagnostics.Debug.Assert(dispose != null);
_state = state;
_dispose = dispose;
}
///
/// Gets a value that indicates whether the object is disposed.
///
public bool IsDisposed => _dispose == null;
///
/// Calls the disposal action if and only if the current instance hasn't been disposed yet.
///
public void Dispose()
{
Interlocked.Exchange(ref _dispose, null)?.Invoke(_state);
_state = default!;
}
}
}