Files
Files copied to clipboard
Code quality: Await is being used inside foreach loop
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
Marking this as ready to build
Consider that doing this in AddAllItemsToSidebar would change the order of the displayed items. Some more changes are required.
I think every scenario needs to be evaluated.
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.
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?
It's been a while sorry I do not recall :)
~~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.