1
0

Finally.cs 2.7 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.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerable
  10. {
  11. public static IAsyncEnumerable<TSource> Finally<TSource>(this IAsyncEnumerable<TSource> source, Action finallyAction)
  12. {
  13. if (source == null)
  14. throw new ArgumentNullException(nameof(source));
  15. if (finallyAction == null)
  16. throw new ArgumentNullException(nameof(finallyAction));
  17. return new FinallyAsyncIterator<TSource>(source, finallyAction);
  18. }
  19. private sealed class FinallyAsyncIterator<TSource> : AsyncIterator<TSource>
  20. {
  21. private readonly Action finallyAction;
  22. private readonly IAsyncEnumerable<TSource> source;
  23. private IAsyncEnumerator<TSource> enumerator;
  24. public FinallyAsyncIterator(IAsyncEnumerable<TSource> source, Action finallyAction)
  25. {
  26. Debug.Assert(source != null);
  27. Debug.Assert(finallyAction != null);
  28. this.source = source;
  29. this.finallyAction = finallyAction;
  30. }
  31. public override AsyncIterator<TSource> Clone()
  32. {
  33. return new FinallyAsyncIterator<TSource>(source, finallyAction);
  34. }
  35. public override async Task DisposeAsync()
  36. {
  37. if (enumerator != null)
  38. {
  39. await enumerator.DisposeAsync().ConfigureAwait(false);
  40. enumerator = null;
  41. finallyAction();
  42. }
  43. await base.DisposeAsync().ConfigureAwait(false);
  44. }
  45. protected override async Task<bool> MoveNextCore()
  46. {
  47. switch (state)
  48. {
  49. case AsyncIteratorState.Allocated:
  50. enumerator = source.GetAsyncEnumerator();
  51. state = AsyncIteratorState.Iterating;
  52. goto case AsyncIteratorState.Iterating;
  53. case AsyncIteratorState.Iterating:
  54. if (await enumerator.MoveNextAsync().ConfigureAwait(false))
  55. {
  56. current = enumerator.Current;
  57. return true;
  58. }
  59. await DisposeAsync().ConfigureAwait(false);
  60. break;
  61. }
  62. return false;
  63. }
  64. }
  65. }
  66. }