Пример #1
0
        private static async Task ForEachCore <T>(
            this IAsyncEnumerator <T> enumerator,
            Func <AsyncLoopContext <T>, Task> enumerationAction
            )
        {
            if (enumerationAction == null)
            {
                throw new ArgumentNullException("enumerationAction");
            }

            var index     = 0L;
            var loopState = new AsyncLoopContext <T>();

            ExceptionDispatchInfo edi = null;

            try
            {
                while (await enumerator.MoveNext().ConfigureAwait(false))
                {
                    loopState.Item  = enumerator.Current;
                    loopState.Index = index;
                    try
                    {
                        await enumerationAction(loopState).ConfigureAwait(false);
                    }
                    catch (Exception e)
                    {
                        edi = ExceptionDispatchInfo.Capture(e);
                        break;
                    }

                    if (loopState.WasBreakCalled)
                    {
                        break;
                    }

                    index++;
                }
            }
            finally
            {
                await enumerator.DisposeAsync(edi?.SourceException);
            }

            edi?.Throw();
        }
Пример #2
0
        public static async Task ForEach <T>(this IAsyncEnumerable <T> enumerable, Func <AsyncLoopContext <T>, Task> enumerationAction)
        {
            if (enumerable == null)
            {
                throw new ArgumentNullException("enumerable");
            }
            if (enumerationAction == null)
            {
                throw new ArgumentNullException("enumerationAction");
            }

            var index      = 0L;
            var doContinue = true;
            var enumerator = enumerable.GetEnumerator();
            var loopState  = new AsyncLoopContext <T>();

            try
            {
                while (doContinue)
                {
                    doContinue = await enumerator.MoveNext().ConfigureAwait(false);

                    if (doContinue)
                    {
                        loopState.Item  = enumerator.Current;
                        loopState.Index = index;

                        await enumerationAction(loopState).ConfigureAwait(false);

                        if (loopState.WasBreakCalled)
                        {
                            break;
                        }

                        index++;
                    }
                }
            }
            finally
            {
                enumerator.Dispose();
            }
        }