using System; using System.Runtime.InteropServices; using System.Threading; [StructLayout(LayoutKind.Sequential)] public struct TimedLock : IDisposable { private readonly object target; private TimedLock(object o) { this.target = o; } public void Dispose() { Monitor.Exit(this.target); } public static TimedLock Lock(object o) { return Lock(o, TimeSpan.FromSeconds(5.0)); } public static TimedLock Lock(object o, TimeSpan timeout) { TimedLock @lock = new TimedLock(o); if (!Monitor.TryEnter(o, timeout)) { Console.WriteLine("Timeout Waiting for lock... @" + o.ToString()); } return @lock; } }