【发布时间】:2018-07-07 07:53:39
【问题描述】:
我正在尝试将 AsParallel() 与 async-await 一起使用,以使应用程序并行处理一系列任务,但由于任务启动了具有大量内存使用的外部进程,因此并发程度受到限制(因此希望等待该过程完成,然后再继续进行系列中的下一个项目)。我在函数ParallelEnumerable.WithDegreeOfSeparation 上看到的大多数文献表明,使用它会在任何时候为并发任务设置最大限制,但我自己的测试似乎表明它完全跳过了限制。
提供一个粗略的例子(WithDegreeOrParallelism() 故意设置为 1 来说明问题):
public class Example
{
private async Task HeavyTask(int i)
{
await Task.Delay(10 * 1000);
}
public async Task Run()
{
int n = 0;
await Task.WhenAll(Enumerable.Range(0, 100)
.AsParallel()
.WithDegreeOfParallelism(1)
.Select(async i =>
{
Interlocked.Increment(ref n);
Console.WriteLine("[+] " + n);
await HeavyTask(i);
Interlocked.Decrement(ref n);
Console.WriteLine("[-] " + n);
}));
}
}
class Program
{
public static void Main(string[] args)
{
Task.Run(async () =>
{
await new Example().Run();
}).Wait();
}
}
据我了解,上面的代码旨在产生如下输出:
[+] 1
[-] 0
[+] 1
[-] 0
...
而是返回:
[+] 1
[+] 2
[+] 3
[+] 4
...
建议它启动列表中的所有任务,然后等待任务返回。
是否有什么特别明显(或不明显)我做错了,这使得 WithDegreeOfParallelism() 似乎被忽略了?
【问题讨论】:
标签: c# async-await .net-4.5