Hi,
We are using this library in our service which generates several reports in parallel threads and we're getting the following exceptions:
System.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 ClosedXML.Excel.IntegerExtensions.ToStringLookup(Int32 value)
This error is caused by those lines of code (of static class ClosedXML.Excel.IntegerExtensions):
private static readonly Dictionary<int, string> intToString = new Dictionary<int, string>();
public static string ToStringLookup(this int value)
{
if (!IntegerExtensions.intToString.ContainsKey(value))
IntegerExtensions.intToString.Add(value, value.ToString((IFormatProvider) IntegerExtensions.nfi));
return IntegerExtensions.intToString[value];
}
I think replace this dictionary by ConcurrentDictionary and use AddOrUpdate method will do the trick :)
Regards,
Maciej.
Comments: ** Comment from web user: SpyderTech02 **
We are using this library in our service which generates several reports in parallel threads and we're getting the following exceptions:
System.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 ClosedXML.Excel.IntegerExtensions.ToStringLookup(Int32 value)
This error is caused by those lines of code (of static class ClosedXML.Excel.IntegerExtensions):
private static readonly Dictionary<int, string> intToString = new Dictionary<int, string>();
public static string ToStringLookup(this int value)
{
if (!IntegerExtensions.intToString.ContainsKey(value))
IntegerExtensions.intToString.Add(value, value.ToString((IFormatProvider) IntegerExtensions.nfi));
return IntegerExtensions.intToString[value];
}
I think replace this dictionary by ConcurrentDictionary and use AddOrUpdate method will do the trick :)
Regards,
Maciej.
Comments: ** Comment from web user: SpyderTech02 **
Something like this should work...
public static class IntegerExtensions
{
private static readonly NumberFormatInfo nfi = CultureInfo.InvariantCulture.NumberFormat;
private static readonly ConcurrentDictionary<Int32, String> intToString = new ConcurrentDictionary<int, string>();
public static String ToStringLookup(this Int32 value)
{
return intToString.GetOrAdd(value, v => v.ToString(nfi));
}
}