3
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

James Wang
  • 179
  • 2
  • 5
  • 10
  • ever heard of `async`? this seems to be the right for this situation. after rewriting your `upload`-mehtod to async you can call somtehing like `await upload(FilePart);` which waits until the operation is finished. – cramopy May 08 '16 at 15:16
  • You could just use `Parallel.For` and limit the concurrency but if `upload` can be called async you have better options. See http://stackoverflow.com/a/11565317/224370 for an example of performing async tasks in parallel. – Ian Mercer May 08 '16 at 15:23
  • 1
    I'm on a phone so only comment but you will want to make your `upload` function async, create a `List` before your `for ` loop, replace `upload(FilePart)` with `myList.Add(upload(FilePart))`, and finally add `await Task.WhenAll(myList)` after your `for` loop. If you haven't accepted an answer in a few hours when I get back to a computer, I will give a full answer. – Jacob Lambert May 08 '16 at 15:29
  • The answer by @Verbon is what I would have suggested, but make sure you listen to the suggestions by CodeNotFound and ScottChamberlain. – Jacob Lambert May 08 '16 at 20:41
  • Read Stephen Cleary's excellent introduction about async-await: http://blog.stephencleary.com/2012/02/async-and-await.html – Harald Coppoolse May 09 '16 at 07:32

1 Answers1

9

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");
}
Verbon
  • 514
  • 4
  • 7