Skip to content

Commit e5d7a79

Browse files
committed
Remove Lock from CallContextLifetimeScope in benefit of ReaderWriterLockSlim
castleproject#565
1 parent 3c9e9e7 commit e5d7a79

File tree

1 file changed

+41
-21
lines changed

1 file changed

+41
-21
lines changed

src/Castle.Windsor/MicroKernel/Lifestyle/Scoped/CallContextLifetimeScope.cs

+41-21
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,7 @@ namespace Castle.MicroKernel.Lifestyle.Scoped
2222
using System.Runtime.Remoting.Messaging;
2323
#endif
2424
using System.Security;
25-
#if !FEATURE_REMOTING
2625
using System.Threading;
27-
#endif
28-
2926
using Castle.Core;
3027
using Castle.Core.Internal;
3128

@@ -50,7 +47,7 @@ public class CallContextLifetimeScope : ILifetimeScope
5047

5148
private readonly Guid contextId = Guid.NewGuid();
5249
private readonly CallContextLifetimeScope parentScope;
53-
private readonly Lock @lock = Lock.Create();
50+
private readonly ReaderWriterLockSlim @lock = new ReaderWriterLockSlim();
5451
private ScopeCache cache = new ScopeCache();
5552

5653
public CallContextLifetimeScope()
@@ -66,25 +63,37 @@ public CallContextLifetimeScope()
6663
[SecuritySafeCritical]
6764
public void Dispose()
6865
{
69-
using (var token = @lock.ForReadingUpgradeable())
66+
@lock.EnterUpgradeableReadLock();
67+
try
7068
{
7169
// Dispose the burden cache
7270
if (cache == null) return;
73-
token.Upgrade();
74-
cache.Dispose();
75-
cache = null;
76-
77-
// Restore the parent scope (if inside one)
78-
if (parentScope != null)
79-
{
80-
SetCurrentScope(parentScope);
81-
}
82-
else
71+
@lock.EnterWriteLock();
72+
try
8373
{
74+
cache.Dispose();
75+
cache = null;
76+
77+
// Restore the parent scope (if inside one)
78+
if (parentScope != null)
79+
{
80+
SetCurrentScope(parentScope);
81+
}
82+
else
83+
{
8484
#if FEATURE_REMOTING
85-
CallContext.FreeNamedDataSlot(callContextKey);
85+
CallContext.FreeNamedDataSlot(callContextKey);
8686
#endif
87+
}
8788
}
89+
finally
90+
{
91+
@lock.ExitWriteLock();
92+
}
93+
}
94+
finally
95+
{
96+
@lock.EnterUpgradeableReadLock();
8897
}
8998

9099
CallContextLifetimeScope @this;
@@ -93,18 +102,29 @@ public void Dispose()
93102

94103
public Burden GetCachedInstance(ComponentModel model, ScopedInstanceActivationCallback createInstance)
95104
{
96-
using (var token = @lock.ForReadingUpgradeable())
105+
@lock.EnterUpgradeableReadLock();
106+
try
97107
{
98108
var burden = cache[model];
99109
if (burden == null)
100110
{
101-
token.Upgrade();
102-
103-
burden = createInstance(delegate { });
104-
cache[model] = burden;
111+
@lock.EnterWriteLock();
112+
try
113+
{
114+
burden = createInstance(delegate { });
115+
cache[model] = burden;
116+
}
117+
finally
118+
{
119+
@lock.ExitWriteLock();
120+
}
105121
}
106122
return burden;
107123
}
124+
finally
125+
{
126+
@lock.ExitUpgradeableReadLock();
127+
}
108128
}
109129

110130
[SecuritySafeCritical]

0 commit comments

Comments
 (0)