Finally.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 EnumerableEx
  11. {
  12. /// <summary>
  13. /// Creates a sequence whose termination or disposal of an enumerator causes a finally action to be executed.
  14. /// </summary>
  15. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  16. /// <param name="source">Source sequence.</param>
  17. /// <param name="finallyAction">Action to run upon termination of the sequence, or when an enumerator is disposed.</param>
  18. /// <returns>Source sequence with guarantees on the invocation of the finally action.</returns>
  19. public static IEnumerable<TSource> Finally<TSource>(this IEnumerable<TSource> source, Action finallyAction)
  20. {
  21. if (source == null)
  22. throw new ArgumentNullException(nameof(source));
  23. if (finallyAction == null)
  24. throw new ArgumentNullException(nameof(finallyAction));
  25. return source.Finally_(finallyAction);
  26. }
  27. private static IEnumerable<TSource> Finally_<TSource>(this IEnumerable<TSource> source, Action finallyAction)
  28. {
  29. try
  30. {
  31. foreach (var item in source)
  32. yield return item;
  33. }
  34. finally
  35. {
  36. finallyAction();
  37. }
  38. }
  39. }
  40. }