Created
September 3, 2012 19:04
-
-
Save davybrion/3612440 to your computer and use it in GitHub Desktop.
code snippets for "Easy Non-Blocking Locking" post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public struct TimedLock : IDisposable | |
| { | |
| private readonly object target; | |
| private TimedLock(object o) | |
| { | |
| target = o; | |
| } | |
| public void Dispose() | |
| { | |
| Monitor.Exit(target); | |
| } | |
| public static TimedLock Lock(object o) | |
| { | |
| return Lock(o, TimeSpan.FromSeconds(5)); | |
| } | |
| public static TimedLock Lock(object o, TimeSpan timeout) | |
| { | |
| return Lock(o, timeout.Milliseconds); | |
| } | |
| public static TimedLock Lock(object o, int milliSeconds) | |
| { | |
| var timedLock = new TimedLock(o); | |
| if (!Monitor.TryEnter(o, milliSeconds)) | |
| { | |
| throw new LockTimeoutException(); | |
| } | |
| return timedLock; | |
| } | |
| } | |
| public class LockTimeoutException : ApplicationException | |
| { | |
| public LockTimeoutException() : base("Timeout waiting for lock") {} | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public virtual T Get(Id id) | |
| { | |
| lock(MonitorObject) | |
| { | |
| if (!Members.ContainsKey(id)) | |
| { | |
| return null; | |
| } | |
| return Members[id]; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public virtual T Get(Id id) | |
| { | |
| using (TimedLock.Lock(MonitorObject, 250)) | |
| { | |
| if (!Members.ContainsKey(id)) | |
| { | |
| return null; | |
| } | |
| return Members[id]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment