Disposables.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. class Disposable : IDisposable
  26. {
  27. private static Action s_nop = () => { };
  28. private Action _dispose;
  29. public Disposable(Action dispose)
  30. {
  31. _dispose = dispose;
  32. }
  33. public static IDisposable Create(IDisposable d1, IDisposable d2)
  34. {
  35. return new BinaryDisposable(d1, d2);
  36. }
  37. public void Dispose()
  38. {
  39. var dispose = Interlocked.Exchange(ref _dispose, s_nop);
  40. dispose();
  41. }
  42. }
  43. class BinaryDisposable : IDisposable
  44. {
  45. private IDisposable _d1;
  46. private IDisposable _d2;
  47. public BinaryDisposable(IDisposable d1, IDisposable d2)
  48. {
  49. _d1 = d1;
  50. _d2 = d2;
  51. }
  52. public void Dispose()
  53. {
  54. var d1 = Interlocked.Exchange(ref _d1, null);
  55. if (d1 != null)
  56. {
  57. d1.Dispose();
  58. var d2 = Interlocked.Exchange(ref _d2, null);
  59. if (d2 != null)
  60. {
  61. d2.Dispose();
  62. }
  63. }
  64. }
  65. }
  66. }