Last active
August 29, 2015 14:08
-
-
Save zaqmor/11d14b7a25b7f7c072fc to your computer and use it in GitHub Desktop.
This file contains hidden or 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(). | |
*/ |
Thanks Keboo. Updated from IList to IEnumerable parameter. Will compare against TPL Parallel.ForEach and revisit.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your first parameter can be IEnumerable.
You may also consider making use of the Parallel.ForEach http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.foreach(v=vs.110).aspx
It does essentially the same thing you are doing, except it will try and be smart about the number of threads it spins up at any one time.