Reputation: 189
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");
});
}
How to create a new task in loop and how to wait all task complete to execute next line code
Upvotes: 3
Views: 11807
Reputation: 545
You should try task combinator 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");
}
Upvotes: 10