Finally.cs 1.7 KB

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