using System;
using System.Reactive.Concurrency;
using System.Threading;

namespace System.Reactive.Disposables
{
	public sealed class ContextDisposable : ICancelable, IDisposable
	{
		public ContextDisposable(SynchronizationContext context, IDisposable disposable)
		{
			if (disposable == null)
			{
				throw new ArgumentNullException("disposable");
			}
			if (context == null)
			{
				throw new ArgumentNullException("context");
			}
			this.Context = context;
			Disposable.SetSingle(ref this._disposable, disposable);
		}

		public SynchronizationContext Context { get; }

		public bool IsDisposed
		{
			get
			{
				return Disposable.GetIsDisposed(ref this._disposable);
			}
		}

		public void Dispose()
		{
			Disposable.TryRelease<SynchronizationContext>(ref this._disposable, this.Context, delegate(IDisposable disposable, SynchronizationContext context)
			{
				context.PostWithStartComplete(delegate(IDisposable d)
				{
					d.Dispose();
				}, disposable);
			});
		}

		private IDisposable _disposable;
	}
}
