using System;
using System.Threading;

// how to use.... set locks to:      use (TimedLock.Lock(obj))     obj = what your locking onto

#if DEBUG
public class TimedLock : IDisposable
#else
public struct TimedLock : IDisposable
#endif
{
    public static TimedLock Lock(object o)
    {
        return Lock(o, TimeSpan.FromSeconds(10)); // set time in seconds here
    }

    public static TimedLock Lock(object o, TimeSpan timeout)
    {
        TimedLock tl = new TimedLock(o);
        if (!Monitor.TryEnter(o, timeout))
        {
#if DEBUG
            System.GC.SuppressFinalize(tl);
#endif
            // throw the exception because the lock did not release properly...
            throw new LockTimeoutException();
        }

        return tl;
    }

    private TimedLock(object o)
    {
        target = o;
    }
    private object target;

    public void Dispose()
    {
        // exit the try monitor
        Monitor.Exit(target);

#if DEBUG
        GC.SuppressFinalize(this);
#endif
    }

#if DEBUG
    ~TimedLock()
    {
        System.Diagnostics.Debug.Fail("Lock was undisposed");
    }
#endif

}
public class LockTimeoutException : Exception
{
    public LockTimeoutException()
        : base("Timeout whilst waiting for lock")  // lock timed out...
    {
    }
}