TheVillageIdiot
TheVillageIdiot

Reputation: 40497

System.Threading.Task Wait doubt

If I am using System.Threading.Task to run parallel tasks like this:

Func<MyResult> func=ComputeResult;

var t = Task.Facroty.StartNew<MyResult>(ComputeResult, 1);//1 is some id
t.Wait();
var tt = Task.Facroty.StartNew<MyResult>(ComputeResult, 2);
tt.Wait();

Will t.Wait() block next statement.

If I am starting few tasks in a loop and want to wait for them all in such a way that tasks inside loop don't block eachother but statement after loop is blocked.

I am using following construct:

var tasks=new List<Task<MyResult>>();

Func<MyResult> func=ComputeResult;

for(int i=0; i<10;i++)
{
    var t=Task.Facroty.StartNew<MyResult>(ComputeResult, i);
    tasks.Add(t);
    //t.Wait(); //SHOULD I CALL WAIT HERE?
}

 //OR THIS BETTER OR EVEN IF THIS WORKS
 foreach(var t in tasks)
 {
      t.Wait();
 }

 //do other stuff

EDIT:- In final form I am using following line instead of last foreach loop.

 Task.WaitAll(tasks.ToArray());

Upvotes: 0

Views: 428

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

How about:

Task.WaitAll(
    Enumerable
        .Range(1, 10)
        .Select(x => Task.Factory.StartNew(arg => 
        {
            // Do the task here
            // arg will obviously be the state object x
            // which will range from 1 to 10
        }, x))
        .ToArray()
);

Upvotes: 1

Related Questions