Last active
August 29, 2015 14:08
-
-
Save zaqmor/11d14b7a25b7f7c072fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
To address trouble with... | |
myList.ForEach( async x => ...do async work... ) | |
where control returns before async operations are complete, | |
consider... | |
*/ | |
namespace Example | |
{ | |
public static async Task ForEachAsync<T>( this IEnumerable<T> list, Func<T, Task> func ) | |
{ | |
await | |
Task.WhenAll( | |
list.Select( | |
item => | |
Task.Run( () => func(item) ))); | |
} | |
} | |
/* | |
The failing... | |
myList.ForEach( async x => ...do async work... ) | |
...becomes... | |
await myList.ForEachAsync( async x => ...do async work... ) | |
... and successfully awaits until all tasks are completed. | |
BONUS! .ForEachAsync() is used fluently with the await/async keywords and is as readable as .ForEach(). | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks Keboo. Updated from IList to IEnumerable parameter. Will compare against TPL Parallel.ForEach and revisit.