我编写了一个方法,它遍历文件列表并从每个文件中提取值并将它们存储到字典中并返回字典。此方法遍历大量文件,因此我收到 ContextSwitchDeadLock 错误。我已经调查了这个错误,我需要使用一个线程来修复这个错误。我是线程的新手,希望得到线程方面的帮助。
我创建了一个新线程并使用委托将参数字典和文件名传递到方法 getValuesNew()。我想知道如何返回字典。我附上了我想调用的方法以及创建新线程的主程序中的代码。任何改进我的代码的建议将不胜感激!
            //dictionary and fileNames are manipulated a bit before use in thread
            Dictionary<string, List<double>> dictionary = new Dictionary<string, List<double>>();
            List<string> fileNames = new List<string>();
            ...
            Thread thread = new Thread(delegate()
            {
                 getValuesNEW(dictionary, fileNames);
            });
            thread.Start();
   //This is the method that I am calling
   public Dictionary<string, List<double>> getValuesNEW(Dictionary<string, List<double>> dictionary, List<string> fileNames)
    {
        foreach (string name in fileNames)
        {
            XmlReader reader = XmlReader.Create(name);
            var collectValues = false;
            string ertNumber = null;
            while (reader.Read())
            {
                if ((reader.NodeType == XmlNodeType.Element))
                {
                    if (reader.Name == "ChannelID" && reader.HasAttributes)
                    {
                        if (dictionary.ContainsKey(sep(reader.GetAttribute("EndPointChannelID"))))
                        {
                            //collectValues = sep(reader.GetAttribute("EndPointChannelID")) == ertNumber;
                            collectValues = true;
                            ertNumber = sep(reader.GetAttribute("EndPointChannelID"));
                        }
                        else
                        {
                            collectValues = false;
                        }
                    }
                    else if (collectValues && reader.Name == "Reading" && reader.HasAttributes)
                    {
                        dictionary[ertNumber].Add(Convert.ToDouble(reader.GetAttribute("Value")));
                    }
                }
            }
        }
        return dictionary;
    }