Task.WhenAll(IEnumerable):任务启动两次?



我偶然发现了 Task.WhenAll 的一个重载,它采用 IEnumerable 作为参数

public static Task WhenAll(IEnumerable<Task<TResult>> tasks)

我想我会用下面的简短程序尝试这个功能。

在测试类中:

// contains the task numbers that has been run
private HashSet<int> completedTasks = new HashSet<int>();
// async function. waits a while and marks that it has been run:
async Task<int> Calculate(int taskNr)
{
string msg = completedTasks.Contains(taskNr) ?
"This task has been run before" :
"This is the first time this task runs";
Console.WriteLine($"Start task {i} {msg}");
await Task.Delay(TimeSpan.FromMilliseconds(100));
Console.WriteLine($"Finished task {taskNr}");
// mark that this task has been run:
completedTasks.Add(taskNr);
return i;
}
// async test function that uses Task.WhenAll(IEnumerable)
public async Task TestAsync()
{
Console.Write("Create the task enumerators... ");
IEnumerable<Task<int>> tasks = Enumerable.Range(1, 3)
.Select(i => Calculate(i));
Console.WriteLine("Done!");
Console.WriteLine("Start Tasks and await");
await Task.WhenAll(tasks);
Console.WriteLine("Finished waiting. Results:");
foreach (var task in tasks)
{
Console.WriteLine(task.Result);
}
}

最后是主程序:

static void Main(string[] args)
{
var testClass = new TestClass();
Task t = Task.Run(() => testClass.TestAsync());
t.Wait();
}

输出如下:

Create the task enumerators... Done!
Start Tasks and wait
Start task 1 This is the first time this task runs
Start task 2 This is the first time this task runs
Start task 3 This is the first time this task runs
Finished task 2
Finished task 3
Finished task 1
Finished waiting. Results:
Start task 1 This task has been run before
Finished task 1
1
Start task 2 This task has been run before
Finished task 2
2
Start task 3 This task has been run before
Finished task 3
3

显然每个任务都运行两次!我做错了什么?

更奇怪的是:如果我在 Task.Whenall 之前使用ToList()枚举任务序列,则该函数按预期工作!

您的问题是延迟执行。更改此行

IEnumerable<Task<int>> tasks = Enumerable.Range(1, 3)
.Select(i => Calculate(i));

var tasks = Enumerable.Range(1, 3)
.Select(i => Calculate(i)).ToList();

Select()不会立即执行"查询",而是返回一个枚举器。仅当使用此枚举器循环访问任务时,才会为序列 1...3 调用内部 lambda。
在您的版本中,每次循环访问tasks时,都会再次调用Calculate(i)并创建新任务。
使用.ToList()枚举器执行一次,生成的Task<int>序列存储在List<Task<int>>中(并且在第二次枚举该列表时不会再次生成(。


调用Task.WhenAll(tasks)此方法循环访问tasks,从而启动每个任务。稍后再次迭代(使用foreach循环输出结果(时,将再次执行查询,从而启动新任务。

最新更新