我正在尝试使用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
内部发生的处理似乎是同步发生的。
我遇到了麻烦-可能是由于缺乏咖啡因-可以找到解决方案。
如果执行foreach的顺序无关紧要,我建议是这样的:
Parallel.ForEach(processingModel.breakpoints.Where(b => (b <= processingModel.width)), (breakpoint) =>
{
ProcessAsync(processingModel, breakpoint);
});