2016-08-16 86 views
0

ConfigurationErrorsException-该进程无法访问该文件“C: eventlog.config”,因为它正被另一个进程使用

我有这段代码总是占用了本身的一种竞争状态尤其是当两个或更多资源正试图同时写入eventlog.config文件时。我搜索了几个频道,但无法解决这个错误。任何人都可以帮助我修改此代码,以便我可以删除竞争条件。

private void UpdateLastEventId(IList<EventLogEntry> entries) 
    { 
     if (entries.Count > 0) 
     { 
      EventLogEntry lastEntry = entries[entries.Count - 1]; 

      Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
      var configSettings = config.AppSettings.Settings; 

      string key = string.Format(CultureInfo.InvariantCulture, "{0}|{1}", _eventLogFilter.EventLog, _eventLogFilter.MD5Hash); 
      if (configSettings[key] == null) 
      { 
       configSettings.Add(key, lastEntry.Index.ToString(CultureInfo.InvariantCulture)); 
      } 
      else 
      { 
       configSettings[key].Value = lastEntry.Index.ToString(CultureInfo.InvariantCulture); 
      } 
      config.Save(ConfigurationSaveMode.Modified);//Error seems to happen here 
     } 
    } 
+0

有你的阅读[在此文档(https://msdn.microsoft.com/en-us/library/ms134088(V = vs.110)的.aspx) – MethodMan

回答

0
private static readonly object _configLogLock = new object(); 
    private void UpdateLastEventId(IList<EventLogEntry> entries) 
    { 
     if (entries.Count > 0) 
     { 
      EventLogEntry lastEntry = entries[entries.Count - 1]; 

      lock (_configLogLock) 
      { 
       Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
       var configSettings = config.AppSettings.Settings; 

       string key = string.Format(CultureInfo.InvariantCulture, "{0}|{1}", _eventLogFilter.EventLog, _eventLogFilter.MD5Hash); 
       if (configSettings[key] == null) 
       { 
        configSettings.Add(key, lastEntry.Index.ToString(CultureInfo.InvariantCulture)); 
       } 
       else 
       { 
        configSettings[key].Value = lastEntry.Index.ToString(CultureInfo.InvariantCulture); 
       } 
       config.Save(ConfigurationSaveMode.Modified);//Error seems to happen here 
      } 
     } 
    } 
+0

你在做什么用'_configLogLock'将信息保存到.config ..?你应该处置所有新创建的对象 – MethodMan

+0

非常感谢你的回复。我现在唯一的争论是如何使用竞争条件测试这个锁语句以写入配置文件?总之,你可以给我一些关于如何模拟竞态条件的想法,以便我可以测试锁定语句。 –

+0

我会创建数百个执行UpdateLastEventId并且并行运行的线程。 – serhiyb

相关问题