Files icon indicating copy to clipboard operation
Files copied to clipboard

Code quality: Await is being used inside foreach loop

Open QuaintMako opened this issue 2 years ago • 7 comments

Description

Through the code, we can find some pieces of code looking like :

foreach (obj o in objectCollection)
{
    await AsyncMethod(o);
}

It is not the most efficient way of performing the tasks, since it means we are waiting for each task to be done before performing the next one. It would be much faster to perform all the task using the Task.WhenAll process.

As an exemple, using this process inside the AddAllItemsToSidebar method allowed for a gain of 15 % in speed.

Concerned code

  • Whole solution

Gains

  • A gain in performances, depending on how often the code is used.

Requirements

Replacing

foreach (obj o in objectCollection)
{
    await AsyncMethod(o);
}

By

var tasksCollections = objectCollection.Select(o=> AsyncMethod(o));
await Task.WhenAll(tasksCollections );

Comments

No response

QuaintMako avatar Oct 21 '22 12:10 QuaintMako

Marking this as ready to build

yaira2 avatar Oct 21 '22 14:10 yaira2

Consider that doing this in AddAllItemsToSidebar would change the order of the displayed items. Some more changes are required.

gave92 avatar Oct 21 '22 17:10 gave92

I think every scenario needs to be evaluated.

yaira2 avatar Oct 21 '22 17:10 yaira2

I did the tests on AddAllItemsToSidebar since it was a pretty easy step to test. Each and every modification will be evaluated for sure, it works only in scenarios where the order of task execution does not matter.

QuaintMako avatar Oct 22 '22 11:10 QuaintMako

Consider that doing this in AddAllItemsToSidebar would change the order of the displayed items. Some more changes are required.

@gave92 do you have anything specific in mind?

yaira2 avatar Feb 06 '24 17:02 yaira2

It's been a while sorry I do not recall :)

gave92 avatar Feb 06 '24 17:02 gave92

~~How about this?~~

await Task.WhenAll(FavoriteItems.AsParallel().AsOrdered().Select(path => AddItemToSidebarAsync(path)));

Edit This is 90% faster on my device but it adds items in the wrong order.

yaira2 avatar Feb 06 '24 18:02 yaira2