Thread.Join()在c#中不起作用

本文关键字:不起作用 Join Thread | 更新日期: 2023-09-27 17:51:21

我有一个CPTproject类和一个CPT类。(CPT是一项测试;这样我就得到了很多数据)。我想从excel文件中读取CPT数据。但是由于它们是大文件,所以我创建了workingThreads来读取它们。我想确保在我离开obtaincts()之前,所有的工作线程都返回了,这就是为什么我在它们上调用Join()。但有时仍然不是所有的workingThreads都返回(即,显示' not all cpt received !')消息。谁能给点提示,可能是什么问题?

    public static void ObtainCPTs(List<string> fileNames)
    {
        CPTproject.numCPTs = fileNames.Count;
        List<Thread> workingThreads = new List<Thread>() ; 
        for (int i = 0; i < fileNames.Count(); i++)
        {
            HelperClass hp = new HelperClass(fileNames[i]); 
            workingThreads.Add(new Thread(hp.GetCPTdataFromExcel)); 
            workingThreads[i].Start();       
        }
        foreach (Thread t in workingThreads)
        {
            t.Join(); 
        }
        if (CPTproject.CPTs.Count() < CPTproject.numCPTs)
        {
            MessageBox.Show("Not all CPTs obtained!"); 
        }
    }

    class HelperClass
    {
       private string _fileName;
       public helperClass(string fileName)
       {
          this._fileName = fileName;
       }
       public void GetCPTdataFromExcel()
       {
          CPT cpt = new CPT();
          //Reads from excel file with address this._fileName
          CPTproject.CPTs.Add(cpt);
       }
    }

Thread.Join()在c#中不起作用

如果CPTproject.CPTs不是线程安全的集合,那么Add方法就不是线程安全的。你应该试着在它周围放一个lock

class HelperClass
{
   private object _locker = new object();
   public void GetCPTdataFromExcel()
   {
      CPT cpt = new CPT();
      //Reads from excel file with address this._fileName
      lock (_locker) {
          CPTproject.CPTs.Add(cpt);
       }
   }
}