Disposables.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. internal sealed class CancellationTokenDisposable : IDisposable
  8. {
  9. private readonly CancellationTokenSource cts = new CancellationTokenSource();
  10. public CancellationToken Token => cts.Token;
  11. public void Dispose()
  12. {
  13. if (!cts.IsCancellationRequested)
  14. {
  15. cts.Cancel();
  16. }
  17. }
  18. }
  19. internal static class Disposable
  20. {
  21. public static IDisposable Create(IDisposable d1, IDisposable d2) => new BinaryDisposable(d1, d2);
  22. public static IDisposable Create(Action action) => new AnonymousDisposable(action);
  23. }
  24. internal sealed class BinaryDisposable : IDisposable
  25. {
  26. private IDisposable _d1;
  27. private IDisposable _d2;
  28. public BinaryDisposable(IDisposable d1, IDisposable d2)
  29. {
  30. _d1 = d1;
  31. _d2 = d2;
  32. }
  33. public void Dispose()
  34. {
  35. var d1 = Interlocked.Exchange(ref _d1, null);
  36. if (d1 != null)
  37. {
  38. d1.Dispose();
  39. var d2 = Interlocked.Exchange(ref _d2, null);
  40. if (d2 != null)
  41. {
  42. d2.Dispose();
  43. }
  44. }
  45. }
  46. }
  47. internal sealed class AnonymousDisposable : IDisposable
  48. {
  49. private Action _action;
  50. public AnonymousDisposable(Action action)
  51. {
  52. _action = action;
  53. }
  54. public void Dispose() => Interlocked.Exchange(ref _action, null)?.Invoke();
  55. }
  56. }