Disposables.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. using System.Threading;
  5. namespace System.Linq
  6. {
  7. class CancellationTokenDisposable : IDisposable
  8. {
  9. private readonly CancellationTokenSource cts = new CancellationTokenSource();
  10. public CancellationToken Token
  11. {
  12. get
  13. {
  14. return cts.Token;
  15. }
  16. }
  17. public void Dispose()
  18. {
  19. if (!cts.IsCancellationRequested)
  20. {
  21. cts.Cancel();
  22. }
  23. }
  24. }
  25. static class Disposable
  26. {
  27. public static IDisposable Create(IDisposable d1, IDisposable d2)
  28. {
  29. return new BinaryDisposable(d1, d2);
  30. }
  31. public static IDisposable Create(Action action)
  32. {
  33. return new AnonymousDisposable(action);
  34. }
  35. }
  36. class BinaryDisposable : IDisposable
  37. {
  38. private IDisposable _d1;
  39. private IDisposable _d2;
  40. public BinaryDisposable(IDisposable d1, IDisposable d2)
  41. {
  42. _d1 = d1;
  43. _d2 = d2;
  44. }
  45. public void Dispose()
  46. {
  47. var d1 = Interlocked.Exchange(ref _d1, null);
  48. if (d1 != null)
  49. {
  50. d1.Dispose();
  51. var d2 = Interlocked.Exchange(ref _d2, null);
  52. if (d2 != null)
  53. {
  54. d2.Dispose();
  55. }
  56. }
  57. }
  58. }
  59. class AnonymousDisposable : IDisposable
  60. {
  61. private Action _action;
  62. public AnonymousDisposable(Action action)
  63. {
  64. _action = action;
  65. }
  66. public void Dispose() => _action();
  67. }
  68. }