c#多线程问题等待线程

Gre*_*egH 2 c# multithreading

在审查了这个论坛上的很多帖子以及其他关于c#multithreading的帖子后,我仍然感到困惑,并且在处理手头的问题时遇到了问题.

我想创建numThreads多个线程来为每个整数执行一个函数documentIds.documentIdsList<int>Count = 100,我想在其中的每个元素上调用RestitchWorker.Restitch documentIds.

我目前的情况如下,但我很困惑如何保持5个线程继续循环通过100个documentIds列表...所有帮助表示赞赏.

for (int i = 0; i < documentIds.Count; i++)
{
    if (threadCount < numThreads)
    {
        var Worker = new RestitchWorker(documentIds.ElementAt(i));
        Thread t_restitchWorker = new Thread(() => Worker.Restitch());
        threadCount++;
        t_restitchWorker.Start();
        t_restitchWorker.Join();
     }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*nes 5

这个问题确实更适合于任务而不是线程.如果你的问题明确地创建线程是没有必要的; 然后线程池可以更高效,因为线程管理可能很昂贵.

任务适合需要松散地并行实现100个长作业的问题,因为它们将汇集线程而不是创建100个显式线程,并且具有支持等待多个任务的易于使用的API.

任务列表

您可以通过创建任务列表并调用来执行此操作System.Threading.Tasks.Task.WaitAll:

var tasks = new List<Task>();

for (int i = 0; i < n; ++i)
{
    tasks.Add(Task.Run(action: SomeLongTask));
}

Task.WaitAll(tasks);
Run Code Online (Sandbox Code Playgroud)

的Parallel.For

然而,更好的方法是这样做,因为它在for循环中,你需要传递一个整数是使用System.Threading.Tasks.Parallel.For:

Parallel.For(0, n, (i) =>
{
   SomeLongTask(i); 
});
Run Code Online (Sandbox Code Playgroud)