使用静态数据返回不同值的线程
本文关键字:线程 返回 静态 数据 | 更新日期: 2023-09-27 17:57:39
我正在制作一个工具,该工具运行在一个大目录上提取数据,并根据语言代码(目录中的第一级文件)启动一个线程。我添加了一个循环,阻止线程添加到数据库中,直到所有线程都完成,因为如果没有它,工具就会陷入死锁。然而,在测试这些数据时,即使测试数据是静态的,DB也存储了错误数量的语言。例如,我有67种语言,但我的数据库中只有48种。我认为问题可能是,我在线程停止之前停止程序运行的循环可能会中断,即在所有线程停止之前向数据库中添加文件,从而在这一过程中丢失语言。我想没有人遇到过类似的问题,或者知道解决这个问题的方法吗?谢谢
//get the languages from the folders
string[] filePaths = Directory.GetDirectories(rootDirectory);
for (int i = 0; i < filePaths.Length; i++)
{
string LCID = filePaths[i].Split('''').Last();
Console.WriteLine(LCID);
//go through files in each folder and sub-folder with threads
Thread t1 = new Thread(() => new HBScanner(new DirectoryInfo(filePaths[i - 1])).HBscan());
t1.Start();
threads.Add(t1);
}
// wait for all threads to complete before proceeding
foreach (Thread thread in threads)
{
while (thread.ThreadState != ThreadState.Stopped)
{
//wait
}
}
首先:制作路径的本地副本,并将其传递到线程中,而不是for循环变量。关闭循环变量被认为是有害的。
我不知道为什么会出现索引超出范围的异常,但也可以通过使用foreach
-循环来避免这种情况。
//get the languages from the folders
string[] filePaths = Directory.GetDirectories(rootDirectory);
foreach(string filePath in filePaths)
{
Console.WriteLine(filePath.Split('''').Last());
string tmpPath = filePath; // <-- local copy
//go through files in each folder and sub-folder with threads
Thread t1 = new Thread(() => new HBScanner(new DirectoryInfo(tmpPath)).HBscan());
t1.Start();
threads.Add(t1);
}
第二:在线程上使用Join
,而不是使用一些自定义的等待代码。
// wait for all threads to complete before proceeding
foreach (Thread thread in threads)
{
thread.Join();
}
最后,确保数据库上没有争用。如果没有关于HBScanner
功能的进一步信息,很难说明可能导致此问题的其他原因。