Skip to content

Instantly share code, notes, and snippets.

@zaqmor
Last active August 29, 2015 14:08
Show Gist options
  • Save zaqmor/11d14b7a25b7f7c072fc to your computer and use it in GitHub Desktop.
Save zaqmor/11d14b7a25b7f7c072fc to your computer and use it in GitHub Desktop.
/*
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().
*/
@Keboo
Copy link

Keboo commented Nov 8, 2014

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.

@zaqmor
Copy link
Author

zaqmor commented Nov 8, 2014

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