我试图使用foreach循环遍历一个集合,并在其中异步执行一个函数。然而,在记录日志时,这似乎仍然以同步方式发生。
这是我的代码:
public async static Task ProcessBreakpointsAsync(ProcessingModel processingModel, bool squeezeOnly = false) {
new LoggerExtensions().LogStatus("Image Extensions: ProcessBreakpointsAsync(processingModel): " + DateTime.Now.ToString(), "Performance");
List<Task> listOfTasks = new List<Task>();
listOfTasks.Add(ProcessAsync(processingModel, 0, true));
foreach (int breakpoint in processingModel.breakpoints.Where(b => (b <= processingModel.width))) {
listOfTasks.Add(ProcessAsync(processingModel, breakpoint));
}
await Task.WhenAll(listOfTasks);
}
private static Task ProcessAsync(ProcessingModel processingModel, int breakpoint, bool squeezeOnly = false) {
new LoggerExtensions().LogStatus("Image Extensions: ProcessAsync(processingModel, " + breakpoint.ToString() + "): " + DateTime.Now.ToString(), "Performance");
ProcessedImageModel optimizedImage = new ProcessedImageModel();
optimizedImage = processingModel.input.Slice(breakpoint, squeezeOnly).Squeeze();
processingModel.cache.Set(optimizedImage.ID.ToString(), optimizedImage, processingModel.memoryCacheEntryOptions);
processingModel.imageCollection.Add(optimizedImage);
return Task.CompletedTask;
}
您将看到我创建了一个任务列表,并等待所有任务完成。这似乎奏效了。然而,根据我正在写的日志,内部发生的处理
ProcessAsync
似乎是同步发生的。
我很难找到解决办法——可能是因为缺乏咖啡因。