在循环完成之前运行代码,线程池c#

时间:2017-02-02 19:06:11

标签: c# .net multithreading

我首先尝试在线程内部执行代码,然后等待for循环完成,然后在for循环之后执行代码。

for (int i = 254; i > 1; i--)
{

    //some code here...

    WaitCallback func = delegate (object state)
    {
        //do something here.... - i want this to finish with the loop first
    };

    ThreadPool.QueueUserWorkItem(func);

}

// this code is executed once the for loop has finished
// however i want it to be done 
// after the thread has finished executing its code and the for loop.

1 个答案:

答案 0 :(得分:7)

您可以使用TPL对工作进行排队,并在循环后立即调用Task.WaitAll

Task[] tasks = new Task[254];
for (int i = 254; i > 1; i--)
{

    //some code here...

    Task task = TaskFactory.StartNew(() => 
    {
        //do something here.... - i want this to finish with the loop first
    });
    tasks[i - 1] = task;
}

Task.WaitAll(tasks);

// do other stuff

TPL最终将使用ThreadPool来完成工作。

PS。我没有运行它或任何东西,所以数组访问可能会出现一个一个错误,但你应该了解这个方法背后的一般想法。

修改

正如评论中提到的eocron,使用Parallel.For也可能是一种选择。