繁体   English   中英

在C#中的foreach循环中实例化线程

[英]Instantiating a Thread within a foreach loop in C#

我有一个函数可以连接到多个SQL Server实例,以从每个服务器获取一组数据,以便在多个环境中比较数据

我有一个连接字符串集合,我正在foreach循环中为集合中的每个连接字符串调用此方法

由于一次要从不同的服务器分别获取数据,这会占用大量时间,我想知道是否每次使用线程都调用此方法的最佳方法是什么?

有两种方法可以做到这一点

1.)创建一组任务,然后执行“等待Task.WaitAll(listOfTasks)”

2.)使用Parallel.ForEach

3.)管理线程

管理线程

我分两个步骤进行操作:

1.)创建线程列表

List<Thread> threads = new List<Thread>();
foreach(var connectionString in ConnectionStrings)
{
   var thread = new Thread(DoWork);
   thread.Start(connectionString);
   threads.Add(thread);

}

2.)将线程连接到当前线程,具有阻塞的作用,直到全部完成。

foreach(var thread in threads)
{
   thread.Join()
}

您可以Join线程并使程序等待所有线程,直到它们完成为止。 在进行下一步之前,这是一个很好的实践。 在下面的代码中查看带有注释的示例:

// list of threads
List<Thread> threads = new List<Thread>();

// list of the results for each thread
List<SomeTypeDto> results = new List<SomeTypeDto>();

foreach(var connectionString in connectionStringList) {

    // create the thread
    Thread thread = new Thread(() => {

        // access the database

        SomeTypeDto result = /* process some result data*/;

        lock (results) {
            results.Add(result);
        }
    });

    threads.Add(thread);
}

// start all threads
foreach (Thread thread in threads) {
    thread.Start();
}

// Wait for all the threads to finish 
foreach (Thread thread in threads) {
    thread.Join();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM