从线程访问 app.config 时出现 IO 错误

IO error when accessing app.config from thread

我正在尝试使用 Task.Run(()=> 方法) 从线程写入我的 app.config,但我得到了一个以下方法中第 2 行的 IO 错误

"System.IO.IOException: 'The process cannot access the file 'WpfApplication1.exe.Config' because it is being used by another process.'"

private static void UpdateCustomConfigSection(string sectionName, string key, string val)
        {
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); //Error happens here

            XmlNode selectSingleNode = xmlDoc.SelectSingleNode($"//{sectionName}/add[@key='{key}']");
            if (selectSingleNode != null && selectSingleNode.Attributes != null)
            {
               selectSingleNode.Attributes["value"].Value = val;
            }

            xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

            ConfigurationManager.RefreshSection(sectionName);
        }

我假设发生这种情况是因为主应用程序线程正在读取文件并阻止线程访问它。有推荐的方法吗?

要使用 app.config,您应该使用 ConfigurationManager
请参见下面的示例:

    private static void UpdateCustomConfigSection(string key, string val)
    {
        Configuration configuration = ConfigurationManager.OpenExeConfiguration(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        configuration.AppSettings.Settings[key].Value = val;
        configuration.Save();
        ConfigurationManager.RefreshSection("appSettings");
    }

但如果问题出在不同的线程上,您可以使用 Dispatcher.Invoke

        Dispatcher.Invoke(() =>
        {
            UpdateCustomConfigSection(sectionName,key, val);
        });

在这种情况下,UpdateCustomConfigSection 应该在 UI 线程中调用,而不管 Dispatcher.Invoke 构造调用在哪里