Disposables.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. }
  32. class BinaryDisposable : IDisposable
  33. {
  34. private IDisposable _d1;
  35. private IDisposable _d2;
  36. public BinaryDisposable(IDisposable d1, IDisposable d2)
  37. {
  38. _d1 = d1;
  39. _d2 = d2;
  40. }
  41. public void Dispose()
  42. {
  43. var d1 = Interlocked.Exchange(ref _d1, null);
  44. if (d1 != null)
  45. {
  46. d1.Dispose();
  47. var d2 = Interlocked.Exchange(ref _d2, null);
  48. if (d2 != null)
  49. {
  50. d2.Dispose();
  51. }
  52. }
  53. }
  54. }
  55. }