// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
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 source.Finally_(finallyAction);
}
private static IEnumerable Finally_(this IEnumerable source, Action finallyAction)
{
try
{
foreach (var item in source)
yield return item;
}
finally
{
finallyAction();
}
}
}
}