当前位置: 动力学知识库 > 问答 > 编程问答 >

multithreading - 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());

网友答案:

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()
);
分享给朋友:
您可能感兴趣的文章:
随机阅读: