@@ -333,8 +333,7 @@ public static BsonClassMap LookupClassMap(Type classType)
333
333
BsonSerializer . ConfigLock . EnterReadLock ( ) ;
334
334
try
335
335
{
336
- BsonClassMap classMap ;
337
- if ( __classMaps . TryGetValue ( classType , out classMap ) )
336
+ if ( __classMaps . TryGetValue ( classType , out var classMap ) )
338
337
{
339
338
if ( classMap . IsFrozen )
340
339
{
@@ -347,19 +346,22 @@ public static BsonClassMap LookupClassMap(Type classType)
347
346
BsonSerializer . ConfigLock . ExitReadLock ( ) ;
348
347
}
349
348
349
+ // automatically create a new classMap for classType and register it (unless another thread does first)
350
+ // do the work of speculatively creating a new class map outside of holding any lock
351
+ var classMapDefinition = typeof ( BsonClassMap < > ) ;
352
+ var classMapType = classMapDefinition . MakeGenericType ( classType ) ;
353
+ var newClassMap = ( BsonClassMap ) Activator . CreateInstance ( classMapType ) ;
354
+ newClassMap . AutoMap ( ) ;
355
+
350
356
BsonSerializer . ConfigLock . EnterWriteLock ( ) ;
351
357
try
352
358
{
353
- BsonClassMap classMap ;
354
- if ( ! __classMaps . TryGetValue ( classType , out classMap ) )
359
+ if ( ! __classMaps . TryGetValue ( classType , out var classMap ) )
355
360
{
356
- // automatically create a classMap for classType and register it
357
- var classMapDefinition = typeof ( BsonClassMap < > ) ;
358
- var classMapType = classMapDefinition . MakeGenericType ( classType ) ;
359
- classMap = ( BsonClassMap ) Activator . CreateInstance ( classMapType ) ;
360
- classMap . AutoMap ( ) ;
361
- RegisterClassMap ( classMap ) ;
361
+ RegisterClassMap ( newClassMap ) ;
362
+ classMap = newClassMap ;
362
363
}
364
+
363
365
return classMap . Freeze ( ) ;
364
366
}
365
367
finally
0 commit comments