[英]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.