Skip to content

Commit 634e847

Browse files
MAIL\p.grigorenkoaensidhe
authored andcommitted
make MsgPackContext thread-safe (fix #77)
1 parent 223084f commit 634e847

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

src/msgpack.light/MsgPackContext.cs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Collections.Concurrent;
23
using System.Collections.Generic;
34
using System.Collections.Immutable;
45
using System.Linq;
@@ -17,17 +18,17 @@ public class MsgPackContext
1718

1819
private readonly ConverterGenerationContext _generatorContext = new ConverterGenerationContext();
1920

20-
private readonly Dictionary<Type, IMsgPackConverter> _converters;
21+
private readonly ConcurrentDictionary<Type, IMsgPackConverter> _converters;
2122

22-
private readonly Dictionary<Type, Type> _genericConverters = new Dictionary<Type, Type>();
23+
private readonly ConcurrentDictionary<Type, Type> _genericConverters = new ConcurrentDictionary<Type, Type>();
2324

24-
private readonly Dictionary<Type, Func<object>> _objectActivators = new Dictionary<Type, Func<object>>();
25+
private readonly ConcurrentDictionary<Type, Func<object>> _objectActivators = new ConcurrentDictionary<Type, Func<object>>();
2526

2627
public MsgPackContext(bool strictParseOfFloat = false, bool convertEnumsAsStrings = true, bool binaryCompatibilityMode = false)
2728
{
2829
_convertEnumsAsStrings = convertEnumsAsStrings;
2930
var numberConverter = new NumberConverter(strictParseOfFloat);
30-
_converters = new Dictionary<Type, IMsgPackConverter>
31+
_converters = new ConcurrentDictionary<Type, IMsgPackConverter>(new Dictionary<Type, IMsgPackConverter>
3132
{
3233
{typeof(MsgPackToken), new MsgPackTokenConverter()},
3334
{typeof (bool), new BoolConverter()},
@@ -60,7 +61,7 @@ public MsgPackContext(bool strictParseOfFloat = false, bool convertEnumsAsString
6061
{typeof (ulong?), new NullableConverter<ulong>()},
6162
{typeof (DateTime?), new NullableConverter<DateTime>()},
6263
{typeof (DateTimeOffset?), new NullableConverter<DateTimeOffset>()}
63-
};
64+
});
6465

6566
foreach (var converter in _converters)
6667
{
@@ -147,7 +148,7 @@ public void RegisterGenericConverter(Type type)
147148
}
148149

149150
var convertedType = converterType.GenericTypeArguments.Single().GetGenericTypeDefinition();
150-
_genericConverters.Add(convertedType, type);
151+
_genericConverters.TryAdd(convertedType, type);
151152
}
152153

153154
public IMsgPackConverter<T> GetConverter<T>()

0 commit comments

Comments
 (0)