CancellationDisposable.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. #if !NO_TPL
  5. using System.Threading;
  6. namespace System.Reactive.Disposables
  7. {
  8. /// <summary>
  9. /// 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.
  10. /// </summary>
  11. public sealed class CancellationDisposable : ICancelable
  12. {
  13. private readonly CancellationTokenSource _cts;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.CancellationDisposable"/> class that uses an existing <seealso cref="T:System.Threading.CancellationTokenSource"/>.
  16. /// </summary>
  17. /// <param name="cts"><seealso cref="T:System.Threading.CancellationTokenSource"/> used for cancellation.</param>
  18. /// <exception cref="ArgumentNullException"><paramref name="cts"/> is null.</exception>
  19. public CancellationDisposable(CancellationTokenSource cts)
  20. {
  21. if (cts == null)
  22. throw new ArgumentNullException(nameof(cts));
  23. _cts = cts;
  24. }
  25. /// <summary>
  26. /// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.CancellationDisposable"/> class that uses a new <seealso cref="T:System.Threading.CancellationTokenSource"/>.
  27. /// </summary>
  28. public CancellationDisposable()
  29. : this(new CancellationTokenSource())
  30. {
  31. }
  32. /// <summary>
  33. /// Gets the <see cref="T:System.Threading.CancellationToken"/> used by this CancellationDisposable.
  34. /// </summary>
  35. public CancellationToken Token
  36. {
  37. get { return _cts.Token; }
  38. }
  39. /// <summary>
  40. /// Cancels the underlying <seealso cref="T:System.Threading.CancellationTokenSource"/>.
  41. /// </summary>
  42. public void Dispose()
  43. {
  44. _cts.Cancel();
  45. }
  46. /// <summary>
  47. /// Gets a value that indicates whether the object is disposed.
  48. /// </summary>
  49. public bool IsDisposed
  50. {
  51. get { return _cts.IsCancellationRequested; }
  52. }
  53. }
  54. }
  55. #endif