How to create task in loop and wait all task complete
private async void button1_Click(object sender, EventArgs e)
{
await BackupFile();
}
public async Task BackupFile()
{
await Task.Run(() =>
{
for (var i = 0; i < partCount; i++)
{
upload(FilePart);//how to creat a new task at here
//i don't want to wait here, i want to upload all part at same time
}
//wait here.
//if total part got 10, then how to wait 10 task complete
//after 10 task complete
Console.WriteLine("Upload Successful");
});
}
如何在循环中创建新任务以及如何等待所有任务完成以执行下一行代码
你应该尝试任务组合器WhenAll:
public async Task BackupFileAsync()
{
var uploadTasks = new List<Task>();
for (var i = 0; i < partCount; i++)
{
var uploadTask = Task.Run(() => upload(FilePart));
uploadTasks.Add(uploadTask)
}
await Task.WhenAll(uploadTasks);
Console.WriteLine("Upload Successful");
}
链接地址: http://www.djcxy.com/p/52802.html
上一篇: c#多个任务不能并行运行
下一篇: 如何在循环中创建任务并等待所有任务完成