Method Finally
| Edit this page View SourceFinally<TSource>(IEnumerable<TSource>, Action)
Creates a sequence whose termination or disposal of an enumerator causes a finally action to be executed.
Declaration
public static IEnumerable<TSource> Finally<TSource>(this IEnumerable<TSource> source, Action finallyAction)
Parameters
Type | Name | Description |
---|---|---|
IEnumerable<TSource> | source | Source sequence. |
Action | finallyAction | Action to run upon termination of the sequence, or when an enumerator is disposed. |
Returns
Type | Description |
---|---|
IEnumerable<TSource> | Source sequence with guarantees on the invocation of the finally action. |
Type Parameters
Name | Description |
---|---|
TSource | Source sequence element type. |
Remarks
This method uses deferred execution and streams its results.
Examples
The following code example demonstrates how to execute an action when an enumeration completes, using Finally
.
var sequence = Enumerable.Range(1, 5);
// Execute an action when enumeration is complete, regardless of success or fail.
var result = sequence
.Do(i => Console.Write($"{i}, "))
.Finally(() => Console.WriteLine("Completed"));
result.Consume();
// This code produces the following output:
// 1, 2, 3, 4, 5, Completed
Exceptions
Type | Condition |
---|---|
ArgumentNullException |
|