工作产生多个线程然后等待,直到全部完成

工作产生多个线程然后等待,直到全部完成

问题描述:

只是想就有关多线程任务的最佳实践的一些建议。

just want some advice on "best practice" regarding multi-threading tasks.

作为一个例子,我们有一个C#的应用程序,在启动时从各种类型表数据库中的读取数据,并存储,我们周围的应用通过一个集合中的信息。这prevents我们从每次需要此信息时访问数据库。

as an example, we have a C# application that upon startup reads data from various "type" table in our database and stores the information in a collection which we pass around the application. this prevents us from hitting the database each time this information is required.

此刻的应用程序是从10表读取数据同步。我真的想有在不同的线程都在并行运行的每个表读取应用程序。应用程序将等待所有的线程与应用程序的启动完成后再继续。

at the moment the application is reading data from 10 tables synchronously. i would really like to have the application read from each table in a different thread all running in parallel. the application would wait for all the threads to complete before continuing with the startup of the application.

我已经调查的BackgroundWorker而只是希望在实现上述一些建议。

i have looked into BackGroundWorker but just want some advice on accomplishing the above.


  1. 是否方法,以加快我们的应用程序
  2. 的启动时间是必然的
  3. 我们如何才能最好地处理所有的线程牢记每个线程的工作是相互独立的,我们只需要等待所有线程完成后再继续。

  1. Does the method sound logical in order to speed up the startup time of our application
  2. How can we best handle all the threads keeping in mind that each thread's work is independent of one another, we just need to wait for all the threads to complete before continuing.

我期待一些答案

本我的preference是通过一个单一的WaitHandle来处理这个问题,并利用连锁,避免锁定在柜台:

My preference for this is to handle this via a single WaitHandle, and use Interlocked to avoid locking on a counter:

class Program
{
    static void Main(string[] args)
    {
        int numThreads = 10;
        ManualResetEvent resetEvent = new ManualResetEvent(false);
        int toProcess = numThreads;

        // Start workers.
        for (int i = 0; i < numThreads; i++)
        {
            new Thread(delegate()
            {
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
                // If we're the last thread, signal
                if (Interlocked.Decrement(ref toProcess) == 0)
                    resetEvent.Set();
            }).Start();
        }

        // Wait for workers.
        resetEvent.WaitOne();
        Console.WriteLine("Finished.");
    }
}

这工作得很好,并扩展到任意数量的线程处理,而不引入锁定。

This works well, and scales to any number of threads processing, without introducing locking.