0

Suppose I have some code that looks like this:

public SomeMethod() {

   foreach (x...)
   {
     if (SomeCondition)
     {
        var SomeVariable = x;
        Task.Factory.StartNew(() => SomeOtherMethod(SomeVariable));
     }
   }

   return SomeValue;
}

If SomeOtherMethod is called and started in a new thread, does a) SomeMethod wait until that thread is finished running before returning or b) the method return and then the threads of SomeOtherMethod just continue on their own even after SomeMethod returned?

Reason I ask is that I need to wait until all SomeOtherMethods finish before exit SomeMethod.

Thanks.

frenchie
  • 51,731
  • 109
  • 304
  • 510

2 Answers2

5

Collect all the tasks in a collection, then call Task.WaitAll on it:

List<Task> tasks = new List<Task>();
foreach (x...)
{
    if (SomeCondition)
    {
        var someVariable = x;
        tasks.Add(Task.Factory.StartNew(() => SomeOtherMethod(someVariable));
     }
}
Task.WaitAll(tasks.ToArray());

Note that in .NET 4.5 when writing an async method, you would use:

await Task.WhenAll(tasks);

as Task.WhenAll itself doesn't block, but returns a task which completes when all the others have. (Note the difference between WhenAll and WaitAll here - very different methods!)

(Additionally, with .NET 4.5 you can use Task.Run instead of Task.Factory.StartNew, just for convenience.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Task.WaitAll can be used to track and wait for all Tasks to complete. StartNew returns a Task. Track all returned values in an array and pass it to WaitAll.

E.G.

        List<Task> tasks = new List<Task>();
        while (condition)
        {
            if (true)
            {                    
                Task temp = Task.Factory.StartNew(() => 0);
                tasks.Add(temp);
            }
            //...
        }

        Task.WaitAll(tasks.ToArray());
P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348