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

Mil*_*lan 0 .net c# 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.
Run Code Online (Sandbox Code Playgroud)

Mar*_*zek 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
Run Code Online (Sandbox Code Playgroud)

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

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

编辑

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