Skip to content

Instantly share code, notes, and snippets.

@zaqmor
Last active August 29, 2015 14:08
Show Gist options
  • Select an option

  • Save zaqmor/11d14b7a25b7f7c072fc to your computer and use it in GitHub Desktop.

Select an option

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().
*/
@zaqmor

zaqmor commented Nov 8, 2014

Copy link
Copy Markdown
Author

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