Skip to content

Commit ddb6bff

Browse files
committed
Fixes #101
1 parent c975f66 commit ddb6bff

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

src/Lifetime/Abstracts/SynchronizedLifetimeManager.cs

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,20 +24,31 @@ public abstract class SynchronizedLifetimeManager : LifetimeManager, IDisposable
2424
{
2525
#region Fields
2626

27-
private readonly object _lockObj = new object();
27+
private readonly object _lock = new object();
28+
29+
/// <summary>
30+
/// This field controlls how long the monitor will wait to
31+
/// enter the lock. It is <see cref="Timeout.Infinite"/> by default or number of
32+
/// milliseconds from 0 to 2147483647.
33+
/// </summary>
34+
public static int ResolveTimeout = Timeout.Infinite;
2835

2936
#endregion
3037

3138
/// <inheritdoc/>
3239
public override object GetValue(ILifetimeContainer container = null)
3340
{
34-
Monitor.Enter(_lockObj);
35-
var result = SynchronizedGetValue(container);
36-
if (NoValue != result)
41+
if (Monitor.TryEnter(_lock, ResolveTimeout))
3742
{
38-
Monitor.Exit(_lockObj);
43+
var result = SynchronizedGetValue(container);
44+
if (NoValue != result)
45+
{
46+
Monitor.Exit(_lock);
47+
}
48+
return result;
3949
}
40-
return result;
50+
else
51+
throw new TimeoutException($"Failed to enter a monitor");
4152
}
4253

4354
/// <summary>
@@ -85,11 +96,11 @@ protected virtual void TryExit()
8596
{
8697
#if !NET40
8798
// Prevent first chance exception when abandoning a lock that has not been entered
88-
if (!Monitor.IsEntered(_lockObj)) return;
99+
if (!Monitor.IsEntered(_lock)) return;
89100
#endif
90101
try
91102
{
92-
Monitor.Exit(_lockObj);
103+
Monitor.Exit(_lock);
93104
}
94105
catch (SynchronizationLockException)
95106
{

0 commit comments

Comments
 (0)