如何在没有async / await的情况下循环异步方法

时间:2012-12-16 17:28:03

标签: c# asynchronous for-loop task-parallel-library

不使用c#async / await功能,在没有阻塞的情况下循环异步操作的最佳方法是什么?

例如,在for循环中异步下载URL的HTML列表。

如果有更多工作的话,我会继续使用TPL继续调用自己的while循环....但是有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

您描述的模式并不错,但您可以将其抽象为辅助方法。类似于ForEachAsyncConvertAllAsync的内容。这将从您的代码中删除循环。这将非必要的复杂性降至最低。


以下是ForEachAsync的实现:

    public static Task ForEachAsync<T>(this TaskFactory factory, IEnumerable<T> items, Func<T, int, Task> getProcessItemTask)
    {
        TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();

        IEnumerator<T> enumerator = items.GetEnumerator();
        int i = 0;

        Action<Task> continuationAction = null;
        continuationAction = ante =>
            {
                if (ante.IsFaulted)
                    tcs.SetException(ante.Exception);
                else if (ante.IsCanceled)
                    tcs.TrySetCanceled();
                else
                    StartNextForEachIteration(factory, tcs, getProcessItemTask, enumerator, ref i, continuationAction);
            };

        StartNextForEachIteration(factory, tcs, getProcessItemTask, enumerator, ref i, continuationAction);

        tcs.Task.ContinueWith(_ => enumerator.Dispose(), TaskContinuationOptions.ExecuteSynchronously);

        return tcs.Task;
    }
    static void StartNextForEachIteration<T>(TaskFactory factory, TaskCompletionSource<object> tcs, Func<T, int, Task> getProcessItemTask, IEnumerator<T> enumerator, ref int i, Action<Task> continuationAction)
    {
        bool moveNext;
        try
        {
            moveNext = enumerator.MoveNext();
        }
        catch (Exception ex)
        {
            tcs.SetException(ex);
            return;
        }

        if (!moveNext)
        {
            tcs.SetResult(null);
            return;
        }

        Task iterationTask = null;
        try
        {
            iterationTask = getProcessItemTask(enumerator.Current, i);
        }
        catch (Exception ex)
        {
            tcs.SetException(ex);
        }

        i++;

        if (iterationTask != null)
            iterationTask.ContinueWith(continuationAction, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, factory.Scheduler ?? TaskScheduler.Default);
    }