Skip to content

Commit a4abcea

Browse files
committed
Fixed race condition in GetTypeInfo method
It was observed that a new ConvertTypeInfo instance was created twice for two threads simultaneously, adding the same type name to the assembly, which caused an ArgumentException "Duplicate type name within an assembly". This is the normal pattern when using a ConcurrentDictionary. To resolve this, it is ensured that the new instance (emitting that type) is only created once. A normal Dictionary and locks are used now.
1 parent 5293d7f commit a4abcea

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

DeepConvert/DeepConvert.cs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -848,8 +848,7 @@ private static DateTime ConvertNumeric(double num, DateNumericKind numericKind,
848848

849849
#endregion Helper methods
850850

851-
private static readonly ConcurrentDictionary<Type, ConvertTypeInfo> typeInfos =
852-
new ConcurrentDictionary<Type, ConvertTypeInfo>();
851+
private static readonly Dictionary<Type, ConvertTypeInfo> typeInfos = new Dictionary<Type, ConvertTypeInfo>();
853852

854853
/// <summary>
855854
/// Returns an object of the specified type whose properties have the values from equally
@@ -906,7 +905,15 @@ public static Dictionary<string, object> ConvertToDictionary(object obj)
906905
/// <returns>The <see cref="ConvertTypeInfo"/> instance to access the type properties.</returns>
907906
private static ConvertTypeInfo GetTypeInfo(Type type)
908907
{
909-
return typeInfos.GetOrAdd(type, t => new ConvertTypeInfo(t));
908+
lock (typeInfos)
909+
{
910+
if (!typeInfos.TryGetValue(type, out var convertTypeInfo))
911+
{
912+
convertTypeInfo = new ConvertTypeInfo(type);
913+
typeInfos.Add(type, convertTypeInfo);
914+
}
915+
return convertTypeInfo;
916+
}
910917
}
911918
}
912919
}

DeepConvert/DeepConvert.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<TargetFrameworks>netstandard2.0;net45</TargetFrameworks>
55
<RootNamespace>Unclassified.Util</RootNamespace>
66
<AssemblyName>Unclassified.DeepConvert</AssemblyName>
7-
<Version>1.4.0</Version>
7+
<Version>1.4.1</Version>
88
<GenerateDocumentationFile>true</GenerateDocumentationFile>
99

1010
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>

0 commit comments

Comments
 (0)