工作产生多个线程然后等待,直到全部完成 [英] Spawn Multiple Threads for work then wait until all finished

查看:177
本文介绍了工作产生多个线程然后等待,直到全部完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于工作产生多个线程然后等待,直到全部完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆