2016-08-16 90 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

相關問題