Need help refactoring this basic asynchronous wait loop

So, I have a business object that supports the "Save" method, which performs some I / O on some device. Then I have a list of those objects that I want to save asynchronously in the package. Now my code is as follows:

public async Task Save() { foreach (var element in Elements) { await element.Save(); } } 

Now this leads to the number of pending n , and I know that each of them causes a bit of processor overhead. I want to eliminate this, and only one of them will wait. How to do refactoring to achieve this?

+4
source share
1 answer

Well, you can call Save() on everything, and then wait for it to finish using Task.WhenAll :

 public async Task Save() { await Task.WhenAll(Elements.Select(x => x.Save()); } 

or if you really are not doing anything, simply:

 public Task Save() { return Task.WhenAll(Elements.Select(x => x.Save()); } 

EDIT: if you want to do this one at a time, use the code that you already have. It is worth noting that the async / await method was designed to wait for a call that actually ends synchronously (for example, getting into the cache or in a dirty check) is really cheap. He does not need to carry out task planning, create a sequel, or something like that. You speak:

If I have a list of 10,000 objects and only 1 is dirty, I will end up with 9999 unnecessary asynchronous expectations, which I suspect will be significant.

As always, suspicions of performance bottlenecks are virtually meaningless - which is important for performance bottlenecks. Have you tried the existing code and measured the cost? If not, I strongly recommend that you do this before changing anything.

+13
source

All Articles