我最近在C#.Net应用程序中遇到了一个问题。未修改的堆栈跟踪如下所示:
2018-09-12 21:08:31,596 [] [112] ERROR PLoggerFactory::RunLogic - Exception : System.Exception: Serialisation errorSystem.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at Block`2.GetConfigFromDB()
at Block`2.GetConfigFromDB()
at Block`2.Begin(IParcelGettable`1 P, Action`1 f)
at Run.<>c__DisplayClass45_0.<RunInNewThread>b__1()
在上面,GetConfigFromDB在堆栈中被调用。但是我已经验证了代码,那里没有任何递归的GetConfigFromDB。这可能吗?
如果需要GetConfigFromDB的代码,请告诉我,我会修改它并分享。
-----编辑-------代码补充
private Dictionary<string, object> GetConfigFromDB()
{
blockConfigJson = controller.BlockConfig.GetConfig(this.BlockInstanceId);
if (String.IsNullOrEmpty(blockConfigJson))
{
return new Dictionary<string, object>();
}
Dictionary<string, object> configDictionary = new Dictionary<string, object>();
try
{
configDictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(blockConfigJson);
foreach (var v in configDictionary)
{
var key = "__" + this.BlockInstanceId + "." + v.Key;
if (SharedConfig.ContainsKey(key))
{
SharedConfig[key] = v.Value;
}
else
{
SharedConfig.Add(key, v.Value);
}
if (v.Key.Trim() == "_extraInfo_")
{
dynamic extraInfo = JsonConvert.DeserializeObject(configDictionary["_extraInfo_"].ToString());
JsonConvert.DeserializeObject<List<Variable>>(extraInfo["Variables"].ToString());
Dictionary<string, string> _variablesTemp = new Dictionary<string, string>();
try
{
_variablesTemp = JsonConvert.DeserializeObject<Dictionary<string, string>>(extraInfo["Variables"].ToString());
}
catch (Exception ex)
{
mLogger.Debug("Variable parsing error " + ex);
}
List<Variable> _variables = new List<Variable>();
foreach (KeyValuePair<string, string> kyp in _variablesTemp)
{
_variables.Add(new Variable()
{
variableName = kyp.Key,
variableValue = kyp.Value
});
}
foreach (Variable _variable in _variables)
{
if (!SharedVariables.ContainsKey(_variable.variableName))
{
SharedVariables.Add(_variable.variableName, _variable.variableValue);
new Caching().Send(_variable.variableName, _EvaluateConfigValue(_variable.variableValue, this.blockConfig, this.SharedConfig, this.SharedVariables, this.propagatedConfig, this.propagatedVariables, this.ControlId));
}
}
}
}
}
catch (Exception ex)
{
configDictionary = new Dictionary<string, object>();
throw;
}
return configDictionary;
}
该堆栈跟踪显示您调用Dictionary<,>.Insert(TKey, TValue, bool)
的方法,但当然您永远不会这样做。你不能,因为这是一个由Dictionary<,>.Add
调用的私有方法,你可以调用它。
启用优化后,堆栈跟踪并不总是100%准确。特别是当调用琐碎的方法时,几乎可以肯定地进行内联。 Dictionary<,>.Add
是一个如此微不足道的方法:除了打电话给Dictionary<,>.Insert
之外别无其他。看起来已经恢复了足够的信息来确定Dictionary<,>.Insert
和GetConfigFromDB
之间有什么东西,但不是什么东西可能。因为没有更好的可用,第二次使用名称GetConfigFromDB
。