CancellationDisposable.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if !NO_TPL
  3. using System.Threading;
  4. namespace System.Reactive.Disposables
  5. {
  6. /// <summary>
  7. /// Represents a disposable resource that has an associated <seealso cref="T:System.Threading.CancellationToken"/> that will be set to the cancellation requested state upon disposal.
  8. /// </summary>
  9. public sealed class CancellationDisposable : ICancelable
  10. {
  11. private readonly CancellationTokenSource _cts;
  12. /// <summary>
  13. /// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.CancellationDisposable"/> class that uses an existing <seealso cref="T:System.Threading.CancellationTokenSource"/>.
  14. /// </summary>
  15. /// <param name="cts"><seealso cref="T:System.Threading.CancellationTokenSource"/> used for cancellation.</param>
  16. /// <exception cref="ArgumentNullException"><paramref name="cts"/> is null.</exception>
  17. public CancellationDisposable(CancellationTokenSource cts)
  18. {
  19. if (cts == null)
  20. throw new ArgumentNullException("cts");
  21. _cts = cts;
  22. }
  23. /// <summary>
  24. /// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.CancellationDisposable"/> class that uses a new <seealso cref="T:System.Threading.CancellationTokenSource"/>.
  25. /// </summary>
  26. public CancellationDisposable()
  27. : this(new CancellationTokenSource())
  28. {
  29. }
  30. /// <summary>
  31. /// Gets the <see cref="T:System.Threading.CancellationToken"/> used by this CancellationDisposable.
  32. /// </summary>
  33. public CancellationToken Token
  34. {
  35. get { return _cts.Token; }
  36. }
  37. /// <summary>
  38. /// Cancels the underlying <seealso cref="T:System.Threading.CancellationTokenSource"/>.
  39. /// </summary>
  40. public void Dispose()
  41. {
  42. _cts.Cancel();
  43. }
  44. /// <summary>
  45. /// Gets a value that indicates whether the object is disposed.
  46. /// </summary>
  47. public bool IsDisposed
  48. {
  49. get { return _cts.IsCancellationRequested; }
  50. }
  51. }
  52. }
  53. #endif