简体   繁体   English

如何使用异步方法正确编写 Parallel.For

[英]How to correctly write Parallel.For with async methods

How would I structure the code below so that the async method gets invoked?我将如何构造下面的代码以便调用异步方法?

Parallel.For(0, elevations.Count(), delegate(int i)
{
   allSheets.AddRange(await BuildSheetsAsync(userID, elevations[i], includeLabels));
});

Parallel.For() doesn't work well with async methods. Parallel.For()不适用于async方法。 If you don't need to limit the degree of parallelism (ie you're okay with all of the tasks executing at the same time), you can simply start all the Task s and then wait for them to complete:如果您不需要限制并行度(即您可以同时执行所有任务),您可以简单地启动所有Task ,然后等待它们完成:

var tasks = Enumerable.Range(0, elevations.Count())
    .Select(i => BuildSheetsAsync(userID, elevations[i], includeLabels));
List<Bitmap> allSheets = (await Task.WhenAll(tasks)).SelectMany(x => x).ToList();

I'd recommend you to take a look at this question I asked a few days ago and ended-up answering myself, basically I was looking for a parallel and asynchronous ForEach method .我建议你看看我几天前问过的这个问题,最后我回答了自己,基本上我正在寻找一个并行和异步的 ForEach 方法

The method uses SemaphoreSlim to process things in parallel and it accepts asynchronous methods as an input action.该方法使用SemaphoreSlim并行处理事物,并接受异步方法作为输入操作。

You might also want to take a look at the two links I have provided at the end of my answer, they have been really helpful for realizing such behavior and they also contain another way of doing this using a Partitioner instead.您可能还想查看我在答案末尾提供的两个链接,它们对实现此类行为非常有帮助,并且还包含另一种使用Partitioner执行此操作的方法。

Personally, I didn't like the Parallel.For because it's a synchronous call as explained in the links I've given;就我个人而言,我不喜欢Parallel.For因为它是一个同步调用,如我提供的链接中所述; I wanted it all 'async' :-)我想要这一切“异步”:-)

Here it is : Asynchronously and parallelly downloading files这是:异步和并行下载文件

You can try this code I'm using.你可以试试我正在使用的这段代码。 it using foreach and SemaphoreSlim to achive parallel asynchronous.它使用 foreach 和 SemaphoreSlim 来实现并行异步。

public static class ParallelAsync
{
    public static async Task ForeachAsync<T>(IEnumerable<T> source, int maxParallelCount, Func<T, Task> action)
    {
        using (SemaphoreSlim completeSemphoreSlim = new SemaphoreSlim(1))
        using (SemaphoreSlim taskCountLimitsemaphoreSlim = new SemaphoreSlim(maxParallelCount))
        {
            await completeSemphoreSlim.WaitAsync();
            int runningtaskCount = source.Count();

            foreach (var item in source)
            {
                await taskCountLimitsemaphoreSlim.WaitAsync();

                Task.Run(async () =>
                {
                    try
                    {
                        await action(item).ContinueWith(task =>
                        {
                            Interlocked.Decrement(ref runningtaskCount);
                            if (runningtaskCount == 0)
                            {
                                completeSemphoreSlim.Release();
                            }
                        });
                    }
                    finally
                    {
                        taskCountLimitsemaphoreSlim.Release();
                    }
                }).GetHashCode();
            }

            await completeSemphoreSlim.WaitAsync();
        }
    }
}

usage:用法:

string[] a = new string[] {
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "10",
    "11",
    "12",
    "13",
    "14",
    "15",
    "16",
    "17",
    "18",
    "19",
    "20"
};

Random random = new Random();

await ParallelAsync.ForeachAsync(a, 2, async item =>
{
    Console.WriteLine(item + " start");

    await Task.Delay(random.Next(1500, 3000));
    Console.WriteLine(item + " end");
});

Console.WriteLine("All finished");

any suggestion please let me know.任何建议请让我知道。

The easiest way to invoke your async method inside Parallel.For is next:Parallel.For调用异步方法的最简单方法是下一个:

Parallel.For(0, elevations.Count(), async i =>
{
   allSheets.AddRange(await BuildSheetsAsync(userID, elevations[i], includeLabels));
});

============== ==============

MarioDS mentioned absolutely right in the comment that in that case you may have unobserved exceptions. MarioDS在评论中完全正确地提到,在这种情况下,您可能会有未观察到的异常。 And this is definitely very important thing which you should always take in mind then have a deal with async delegates.这绝对是非常重要的事情,您应该始终牢记这一点,然后与异步委托打交道。

In this case if you think that you will have exceptions you can use try/catch block inside delegate.在这种情况下,如果您认为会有异常,您可以在委托中使用try/catch块。 Or in some cases if your situation is good for it you can subscribe on TaskScheduler.UnobservedTaskException event.或者在某些情况下,如果您的情况适合,您可以订阅TaskScheduler.UnobservedTaskException事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM