2

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

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

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

4

1 回答 1

2

您描述的模式还不错,但是您可以将其抽象为辅助方法。像ForEachAsync或之类的东西ConvertAllAsync。这从您的代码中删除了循环。这将非必要的复杂性降至最低。


这是一个实现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);
    }
于 2012-12-16T19:37:33.013 回答