Reputation: 21
I have a CPTproject class and a CPT class. (CPT is a test; doing which I get a lot of data). I want to read the CPT data from excel files. But since they are large files, I am creating workingThreads to read them conconcerruntly. I want to make sure before I leave the ObtainCPTs() all the workingThreads have returned, that is why I'm calling Join() on them. But still sometimes not all the workingThreads are returning (i.e., the 'Not all CPTs obtained!') message is shown. Can anybody give some hint on what might be the problem?
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);
}
}
Upvotes: 0
Views: 939
Reputation: 161801
If CPTproject.CPTs
is not a thread-safe collection, then the Add
method is not thread-safe. You should try putting a lock
around it
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);
}
}
}
Upvotes: 2