0

I am trying to loop through a collection using foreach and execute a function asyncronously inside it. However, when logging it appears that this is still occurring in a synchronous fashion.

This is my code:

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;  
}

You will see I create a list of tasks and await when all tasks are complete. This appears to work. However --according to the logging I am writing out -- the processing that happens inside ProcessAsync appears to happen synchronously.

I am having trouble -- perhaps due to a lack of caffeine -- to see what a solution would be.

eat-sleep-code
  • 4,753
  • 13
  • 52
  • 98

1 Answers1

1

If the order of executing the foreach doesn't matter i suggest something like this:

 Parallel.ForEach(processingModel.breakpoints.Where(b => (b <= processingModel.width)), (breakpoint) =>
            {
                ProcessAsync(processingModel, breakpoint);
            });
J. Guerra
  • 86
  • 4
  • 2
    Note that in general it is bad suggestion as `Parallel.ForEach` is not exactly compatible with `async`/`await`. Fortunately in OP's case there is no asynchronous code in they `ProcessAsync` method so this approach is ok. DO NOT use this approach for really asynchronous methods without reading https://stackoverflow.com/questions/23137393/parallel-foreach-and-async-await – Alexei Levenkov Oct 07 '19 at 22:00