我有一个Parallel.ForEach用于读取许多文件的内容。在循环之后,我的结果有时会有差异 有时候我的列表中有一个元素是“null”或者是文件的完整路径......
为什么会这样?
示例:
dir中的文件: 67
结果1:找到具有特定内容的23个文件
然后我跳回到我方法的开头......
结果2:找到具有特定内容的25个文件
这是我的代码
private List<string> GetFileNames() {
if (Files.Count > 0)
Files.Clear();
XmlDocument xmlDoc = new XmlDocument();
XmlNodeList dataNodes; // = xmlDoc.SelectNodes("/ELO2BDE/TimeSlots/TimeSlot");
string[] tempFiles = Directory.GetFiles(MyXMLLocation, "*_" + cbTB.Text + "_Logbook.xml", SearchOption.TopDirectoryOnly);
DateTime firstday = dtpFrom.Value;
DateTime lastday = dtpTill.Value;
nodays.AddRange(DateRange(firstday.Date, lastday.Date));
if (tempFiles.Length > 0) {
for (int i = 0; i < tempFiles.Length; i++) {
dataNodes = xmlDoc.SelectNodes("/ELO2BDE/TimeSlots/TimeSlot");
xmlDoc.Load(tempFiles[i]);
if (firstday <= lastday) {
Parallel.ForEach(dataNodes.Cast<XmlNode>(), (XmlNode node) => {
DateTime date = Convert.ToDateTime(node["StartTime"].InnerText);
string filename = Path.GetFileNameWithoutExtension(tempFiles[i] + ".xml");
if (date.Date >= firstday.Date && date.Date <= lastday.Date && !Files.Contains(filename)) {
Files.Add(filename);
firstday = firstday.AddDays(1);
}
nodays.Remove(date.Date);
});
}
}
}
if (Files.Count <= 0) {
MessageBox.Show("No days exported for this time period.");
return null;
} else {
Files.Sort();
return Files;
}
}