Skip to content

Instantly share code, notes, and snippets.

@ehsan-davoudi
Created January 29, 2014 13:54
Show Gist options
  • Select an option

  • Save ehsan-davoudi/8688427 to your computer and use it in GitHub Desktop.

Select an option

Save ehsan-davoudi/8688427 to your computer and use it in GitHub Desktop.
Run List of Tasks Asynchronously with async/await in C#
Assume we have a list of tasks and we need to run them asynchronously, we can use below code:
var toDoTasks = new List<OurTask>();
IEnumerable<Task<int>> taskListQuery = from toDoTask in toDoTasks select DoSomething(ourTask);
List<Task<int>> taskList = taskListQuery.ToList();
while (taskList.Count > 0)
{
Task<int> firstFinishedTask = await Task.WhenAny(taskList);
downloadTasks.Remove(firstFinishedTask);
int taskList = await firstFinishedTask;
}
Task<int> DoSomething(OurTask ourTask)
{
return Task.Run(() =>
{
//do your job here
return 1;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment