团队,
我有这样一段代码,它总是在某种竞争条件下将自己绑定起来,尤其是当两个或多个资源试图同时写入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
}
}
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
}
}
}