Finally.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class AsyncEnumerable
  11. {
  12. public static IAsyncEnumerable<TSource> Finally<TSource>(this IAsyncEnumerable<TSource> source, Action finallyAction)
  13. {
  14. if (source == null)
  15. throw new ArgumentNullException(nameof(source));
  16. if (finallyAction == null)
  17. throw new ArgumentNullException(nameof(finallyAction));
  18. return CreateEnumerable(
  19. () =>
  20. {
  21. var e = source.GetEnumerator();
  22. var cts = new CancellationTokenDisposable();
  23. var r = new Disposable(finallyAction);
  24. var d = Disposable.Create(cts, e, r);
  25. return CreateEnumerator(
  26. ct => e.MoveNext(ct),
  27. () => e.Current,
  28. d.Dispose,
  29. r
  30. );
  31. });
  32. }
  33. }
  34. }