Skip to content

Commit

Permalink
Use async iterators in Finally.
Browse files Browse the repository at this point in the history
  • Loading branch information
bartdesmet committed Jan 29, 2019
1 parent c66fdda commit b48137d
Showing 1 changed file with 41 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace System.Linq
Expand All @@ -17,7 +18,26 @@ public static IAsyncEnumerable<TSource> Finally<TSource>(this IAsyncEnumerable<T
if (finallyAction == null)
throw Error.ArgumentNull(nameof(finallyAction));

#if USE_ASYNC_ITERATOR
return Create(Core);

async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
{
try
{
await foreach (TSource item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
{
yield return item;
}
}
finally
{
finallyAction();
}
}
#else
return new FinallyAsyncIterator<TSource>(source, finallyAction);
#endif
}

public static IAsyncEnumerable<TSource> Finally<TSource>(this IAsyncEnumerable<TSource> source, Func<Task> finallyAction)
Expand All @@ -27,11 +47,31 @@ public static IAsyncEnumerable<TSource> Finally<TSource>(this IAsyncEnumerable<T
if (finallyAction == null)
throw Error.ArgumentNull(nameof(finallyAction));

#if USE_ASYNC_ITERATOR
return Create(Core);

async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
{
try
{
await foreach (TSource item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
{
yield return item;
}
}
finally
{
await finallyAction().ConfigureAwait(false);
}
}
#else
return new FinallyAsyncIteratorWithTask<TSource>(source, finallyAction);
#endif
}

// REVIEW: No cancellation support for finally action.

#if !USE_ASYNC_ITERATOR
private sealed class FinallyAsyncIterator<TSource> : AsyncIterator<TSource>
{
private readonly Action _finallyAction;
Expand Down Expand Up @@ -148,4 +188,5 @@ protected override async ValueTask<bool> MoveNextCore()
}
}
}
#endif
}

0 comments on commit b48137d

Please sign in to comment.