2
0

CancellationDisposable.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // original code from GitHub Reactive-Extensions/Rx.NET
  2. // some modified.
  3. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  4. #if (NETFX_CORE || NET_4_6 || NET_STANDARD_2_0 || UNITY_WSA_10_0)
  5. using System;
  6. using System.Threading;
  7. namespace UniRx
  8. {
  9. /// <summary>
  10. /// 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.
  11. /// </summary>
  12. public sealed class CancellationDisposable : ICancelable
  13. {
  14. private readonly CancellationTokenSource _cts;
  15. /// <summary>
  16. /// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.CancellationDisposable"/> class that uses an existing <seealso cref="T:System.Threading.CancellationTokenSource"/>.
  17. /// </summary>
  18. /// <param name="cts"><seealso cref="T:System.Threading.CancellationTokenSource"/> used for cancellation.</param>
  19. /// <exception cref="ArgumentNullException"><paramref name="cts"/> is null.</exception>
  20. public CancellationDisposable(CancellationTokenSource cts)
  21. {
  22. if (cts == null)
  23. throw new ArgumentNullException("cts");
  24. _cts = cts;
  25. }
  26. /// <summary>
  27. /// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.CancellationDisposable"/> class that uses a new <seealso cref="T:System.Threading.CancellationTokenSource"/>.
  28. /// </summary>
  29. public CancellationDisposable()
  30. : this(new CancellationTokenSource())
  31. {
  32. }
  33. /// <summary>
  34. /// Gets the <see cref="T:System.Threading.CancellationToken"/> used by this CancellationDisposable.
  35. /// </summary>
  36. public CancellationToken Token
  37. {
  38. get { return _cts.Token; }
  39. }
  40. /// <summary>
  41. /// Cancels the underlying <seealso cref="T:System.Threading.CancellationTokenSource"/>.
  42. /// </summary>
  43. public void Dispose()
  44. {
  45. _cts.Cancel();
  46. }
  47. /// <summary>
  48. /// Gets a value that indicates whether the object is disposed.
  49. /// </summary>
  50. public bool IsDisposed
  51. {
  52. get { return _cts.IsCancellationRequested; }
  53. }
  54. }
  55. }
  56. #endif