Thread.Join()无法在C#中工作

时间:2014-03-22 02:40:57

标签: c# multithreading join

我有一个CPT项目类和一个CPT类。 (CPT是一项测试;我从中获得了大量数据)。我想从excel文件中读取CPT数据。但由于它们是大文件,我正在创建workingThreads以便以一致的方式阅读它们。我想确保在离开ObtainCPTs()之前所有的workThread都返回了,这就是我在它们上面调用Join()的原因。但有时仍然不是所有的workThread都返回(即,显示'并非所有CPT获得!')消息。任何人都可以对可能出现的问题给出一些暗示吗?

    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);
       }
    }

1 个答案:

答案 0 :(得分:2)

如果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);
       }
   }
}