Permalink
Browse files

Protect AutoMappingStore from Threading issues.

  • Loading branch information...
1 parent 20fa57e commit f66208199310d254865e4c2d5b0c36e8ec7bf045 @lanwin lanwin committed Aug 30, 2010
Showing with 33 additions and 12 deletions.
  1. +33 −12 source/MongoDB/Configuration/Mapping/AutoMappingStore.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Threading;
using MongoDB.Configuration.Mapping.Auto;
using MongoDB.Configuration.Mapping.Model;
@@ -11,6 +12,7 @@ public class AutoMappingStore : IMappingStore
{
private readonly IAutoMapper _autoMapper;
private readonly Dictionary<Type, IClassMap> _autoMaps;
+ private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
private readonly IMappingStore _wrappedMappingStore;
/// <summary>
@@ -71,23 +73,42 @@ public AutoMappingStore(IAutoMapper autoMapper, IMappingStore mappingStore)
/// <returns></returns>
public IClassMap GetClassMap(Type classType)
{
- IClassMap classMap;
-
- if(_autoMaps.TryGetValue(classType, out classMap))
- return classMap;
-
- if(_wrappedMappingStore != null)
+ try
{
- classMap = _wrappedMappingStore.GetClassMap(classType);
- if(classMap != null)
+ _lock.EnterUpgradeableReadLock();
+
+ IClassMap classMap;
+ if(_autoMaps.TryGetValue(classType, out classMap))
return classMap;
- }
- classMap = _autoMapper.CreateClassMap(classType, GetClassMap);
+ if(_wrappedMappingStore != null)
+ {
+ classMap = _wrappedMappingStore.GetClassMap(classType);
+ if(classMap != null)
+ return classMap;
+ }
+
+ classMap = _autoMapper.CreateClassMap(classType, GetClassMap);
- _autoMaps.Add(classType, classMap);
+ try
+ {
+ _lock.EnterWriteLock();
- return classMap;
+ _autoMaps.Add(classType, classMap);
+
+ return classMap;
+ }
+ finally
+ {
+ if(_lock.IsWriteLockHeld)
+ _lock.ExitWriteLock();
+ }
+ }
+ finally
+ {
+ if(_lock.IsUpgradeableReadLockHeld)
+ _lock.ExitUpgradeableReadLock();
+ }
}
}
}

0 comments on commit f662081

Please sign in to comment.