Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
  });
}

How to create a new task in loop and how to wait all task complete to execute next line code

like image 833
James Wang Avatar asked Aug 27 '26 03:08

James Wang


1 Answers

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");
}
like image 132
Verbon Avatar answered Aug 29 '26 17:08

Verbon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!