// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT License. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace System.Linq { public static partial class EnumerableEx { /// /// Creates a sequence whose termination or disposal of an enumerator causes a finally action to be executed. /// /// Source sequence element type. /// Source sequence. /// Action to run upon termination of the sequence, or when an enumerator is disposed. /// Source sequence with guarantees on the invocation of the finally action. public static IEnumerable Finally(this IEnumerable source, Action finallyAction) { if (source == null) throw new ArgumentNullException(nameof(source)); if (finallyAction == null) throw new ArgumentNullException(nameof(finallyAction)); return FinallyCore(source, finallyAction); } private static IEnumerable FinallyCore(IEnumerable source, Action finallyAction) { try { foreach (var item in source) { yield return item; } } finally { finallyAction(); } } } }