-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTimedLock.cs
More file actions
executable file
·299 lines (248 loc) · 10.1 KB
/
TimedLock.cs
File metadata and controls
executable file
·299 lines (248 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// Copyright 2009 - 2012 Andrew Rondeau
// This code is released under the Simple Public License (SimPL) 2.0. Some additional privelages are granted.
// For more information, see either DefaultFiles/Docs/license.wchtml or /Docs/license.wchtml
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
// based on code published at:
// http://www.interact-sw.co.uk/iangblog/2004/04/26/yetmoretimedlocking
// ADR:
// An interesting thing to do would be to add deadlock detection like what is described here:
// http://msdn.microsoft.com/en-us/magazine/cc163352.aspx
// I'd have integrated their code into this system, except for the fact that I think MS's license
// essentially forbids using their code in an open source project.
namespace ObjectCloud.Common.Threading
{
// Thanks to Eric Gunnerson for recommending this be a struct rather
// than a class - avoids a heap allocation.
// Thanks to Change Gillespie and Jocelyn Coulmance for pointing out
// the bugs that then crept in when I changed it to use struct...
// Thanks to John Sands for providing the necessary incentive to make
// me invent a way of using a struct in both release and debug builds
// without losing the debug leak tracking.
public struct TimedLock : IDisposable
{
/// <value>
/// The default timeout to use when aquireing a TimedLock. This is 10 seconds, unless set
/// </value>
public static TimeSpan DefaultAquireLockTimeout
{
get { return _DefaultAquireLockTimeout; }
set { _DefaultAquireLockTimeout = value; }
}
private static TimeSpan _DefaultAquireLockTimeout = TimeSpan.FromSeconds(10);
/// <value>
/// The default maximum amount of time that a lock can be held. If the lock is held longer then this, an attempt is made to stop the thread holding the lock. This is disabled by default
/// </value>
public static TimeSpan? DefaultLockAquiredTimeout
{
get { return _DefaultLockAquiredTimeout; }
set { _DefaultLockAquiredTimeout = value; }
}
private static TimeSpan? _DefaultLockAquiredTimeout = null;
/// <value>
/// Default delegate called when a thread holds a lock too long. Be default, this is TimedLock.AbortThread, which tries to abort the thread
/// </value>
public static LockingThreadTimeoutDelegate LockingThreadTimeoutDelegate
{
get { return _LockingThreadTimeoutDelegate; }
set { _LockingThreadTimeoutDelegate = value; }
}
private static LockingThreadTimeoutDelegate _LockingThreadTimeoutDelegate = AbortThread;
/// <value>
/// Called when AbortThread can not abort a thread, defaults to AbortThreadFailed, which attempts to break into the debugger if attached
/// </value>
public static LockingThreadTimeoutDelegate LockingThreadAbortFailed
{
get { return _LockingThreadAbortFailed; }
set { _LockingThreadAbortFailed = value; }
}
private static LockingThreadTimeoutDelegate _LockingThreadAbortFailed = AbortThreadFailed;
public static TimedLock Lock(object o)
{
return CreateLock(o, DefaultAquireLockTimeout, DefaultLockAquiredTimeout, LockingThreadTimeoutDelegate);
}
public static TimedLock Lock(object o, TimeSpan timeout)
{
return CreateLock(o, timeout, DefaultLockAquiredTimeout, LockingThreadTimeoutDelegate);
}
public static TimedLock Lock(object o, TimeSpan timeout, TimeSpan lockAquiredTimeout)
{
return CreateLock(o, timeout, lockAquiredTimeout, LockingThreadTimeoutDelegate);
}
public static TimedLock Lock(object o, TimeSpan timeout, TimeSpan lockAquiredTimeout, LockingThreadTimeoutDelegate lockingThreadTimeoutDelegate)
{
return CreateLock(o, timeout, lockAquiredTimeout, lockingThreadTimeoutDelegate);
}
/// <summary>
/// A timer used to watch for when a thread holds on to the lock too long
/// </summary>
private Timer Timer;
/// <summary>
/// The delegate used when THIS thread holds on to its lock too long
/// </summary>
private LockingThreadTimeoutDelegate myLockingThreadTimeoutDelegate;
/*#if DEBUG
/// <summary>
/// Guid that identifies the lock; this is only present in Debug mode
/// </summary>
public Guid ID;
#endif*/
/// <summary>
/// The thread that is holding the lock
/// </summary>
private Thread Thread;
private static TimedLock CreateLock(object o, TimeSpan timeout, TimeSpan? aquiredLockTimeout, LockingThreadTimeoutDelegate lockingThreadTimeoutDelegate)
{
TimedLock toReturn = new TimedLock();
toReturn.Thread = Thread.CurrentThread;
toReturn.target = o;
//string lockInformation = string.Format(
// "\n\n\nThreadID: {0}\ntype of lock object:{2},Call stack: {2}\n\n\n",
// Thread.CurrentThread.ManagedThreadId,
// o.GetType().FullName,
// Environment.StackTrace);
if (!Monitor.TryEnter(o, timeout))
{
//string lockHolderInformation;
//lock (LockHolders)
// if (!LockHolders.TryGetValue(o, out lockHolderInformation))
// lockHolderInformation = "not available";
//throw new LockTimeoutException(o, lockHolderInformation);
throw new LockTimeoutException(o);
}
//lock (LockHolders)
// LockHolders[o] = lockInformation;
toReturn.myLockingThreadTimeoutDelegate = lockingThreadTimeoutDelegate;
if (null != aquiredLockTimeout)
toReturn.Timer = new Timer(toReturn.Timeout, null, Convert.ToInt32(aquiredLockTimeout.Value.TotalMilliseconds), -1);
else
toReturn.Timer = null;
/*#if DEBUG
toReturn.ID = Guid.NewGuid();
OnLockCreated(toReturn);
#endif*/
return toReturn;
}
//static Dictionary<object, string> LockHolders = new Dictionary<object, string>();
/// <summary>
/// This is the target of the lock
/// </summary>
public object Target
{
get { return target; }
}
private object target;
public void Dispose()
{
//lock (LockHolders)
// LockHolders.Remove(Target);
Monitor.Exit(target);
Thread = null;
if (null != Timer)
lock (Timer)
if (null != Timer)
{
Timer.Dispose();
Timer = null;
}
/*#if DEBUG
OnLockComplete(this);
#endif*/
}
private void Timeout(object state)
{
if (null != Timer)
lock (Timer)
if (null != Timer)
{
Timer.Dispose();
Timer = null;
}
Thread thread = Thread;
if (null != thread)
myLockingThreadTimeoutDelegate(thread);
}
/// <summary>
/// Aborts whatever thread is passed in, used when a thread holds a lock too long
/// </summary>
/// <param name="toAbort">
/// A <see cref="Thread"/>
/// </param>
public static void AbortThread(Thread toAbort)
{
if (null == toAbort)
return;
toAbort.Abort();
DateTime timeout = DateTime.UtcNow.AddSeconds(15);
while (toAbort.ThreadState != ThreadState.Aborted)
{
if (timeout < DateTime.UtcNow)
{
LockingThreadAbortFailed(toAbort);
return;
}
}
}
/// <summary>
/// Attempts to hop into the debugger if a thread that is holding a lock can not be aborted
/// </summary>
/// <param name="toAbort">
/// A <see cref="Thread"/>
/// </param>
public static void AbortThreadFailed(Thread toAbort)
{
if (System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
}
/*#if DEBUG
/// <summary>
/// Occurs whenever a lock is created. This is only availalbe in debug builds
/// </summary>
public static event Action<TimedLock> LockCreated;
internal static void OnLockCreated(TimedLock timedLock)
{
if (null != LockCreated)
LockCreated(timedLock);
}
/// <summary>
/// Occurs whenever a lock is complete. This is only availalbe in debug builds
/// </summary>
public static event Action<TimedLock> LockComplete;
internal static void OnLockComplete(TimedLock timedLock)
{
if (null != LockComplete)
LockComplete(timedLock);
}
#endif*/
}
/// <summary>
/// Thrown if a there is a timeout when trying to aquire a lock
/// </summary>
public class LockTimeoutException : ApplicationException
{
/// <value>
/// The object that was attempted to be locked
/// </value>
public object AttemptedToLock
{
get { return _AttemptedToLock; }
}
private readonly object _AttemptedToLock;
/*public LockTimeoutException(object attemptedToLock, string lockHolderInformation)
: base("Timeout waiting for lock, lock information:\n" + lockHolderInformation)
{
_AttemptedToLock = attemptedToLock;
}*/
public LockTimeoutException(object attemptedToLock)
: base("Timeout waiting for lock")
{
_AttemptedToLock = attemptedToLock;
}
}
/// <summary>
/// Delegate that's used when a thread holds onto a lock too long
/// </summary>
public delegate void LockingThreadTimeoutDelegate(Thread blockingThread);
}