using System;
using System.Threading;

namespace System.Reactive.Disposables
{
	internal sealed class AnonymousDisposable<TState> : ICancelable, IDisposable
	{
		public AnonymousDisposable(TState state, Action<TState> dispose)
		{
			this._state = state;
			this._dispose = dispose;
		}

		public bool IsDisposed
		{
			get
			{
				return this._dispose == null;
			}
		}

		public void Dispose()
		{
			Action<TState> action = Interlocked.Exchange<Action<TState>>(ref this._dispose, null);
			if (action != null)
			{
				action(this._state);
			}
			this._state = default(TState);
		}

		private TState _state;

		private volatile Action<TState> _dispose;
	}
}
