1
0

Disposables.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT 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();
  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. d2?.Dispose();
  41. }
  42. }
  43. }
  44. internal sealed class AnonymousDisposable : IDisposable
  45. {
  46. private Action? _action;
  47. public AnonymousDisposable(Action action)
  48. {
  49. _action = action;
  50. }
  51. public void Dispose() => Interlocked.Exchange(ref _action, null)?.Invoke();
  52. }
  53. }