/// <summary> /// Attempts to obtain a lock on the specified object for up to /// the specified timeout. /// </summary> /// <param name="o"></param> /// <param name="timeout"></param> /// <returns></returns> public static TimedLock Lock(object o, TimeSpan timeout) { Thread.BeginCriticalRegion(); var tl = new TimedLock(o); if (!Monitor.TryEnter(o, timeout)) { // Failed to acquire lock. #if DEBUG GC.SuppressFinalize(tl.leakDetector); throw new LockTimeoutException(o); #else throw new LockTimeoutException(); #endif } return(tl); }
public static object GetOrAddUntyped(this ICache cache, string key, Func <object> add, TimeSpan?timeout = null) { var item = cache.Get(key); if (item == null) { if (add == null) { return(null); } using (TimedLock.Lock(CacheLockScope.AcquireLock <object>(key), timeout ?? Depot.ContentionTimeout)) { var itemToAdd = add(); if (itemToAdd != null) { cache.Add(key, itemToAdd); } } return(cache.Get(key)); } return(item); }
public static T GetOrAddTyped <T>(this ICache cache, string key, Func <T> add, TimeSpan?timeout = null) where T : class { var item = cache.Get(key); if (item == null) { if (add == null) { return(default(T)); } using (TimedLock.Lock(CacheLockScope.AcquireLock <T>(key), timeout ?? Depot.ContentionTimeout)) { var itemToAdd = add(); if (itemToAdd != null) { cache.Add(key, itemToAdd); } } return(cache.Get <T>(key)); } return((T)item); }
/// <summary> /// Attempts to obtain a lock on the specified object for up to /// the specified timeout. /// </summary> /// <param name="o"></param> /// <param name="timeout"></param> /// <returns></returns> public static TimedLock Lock(object o, TimeSpan timeout) { Thread.BeginCriticalRegion(); var tl = new TimedLock(o); if (!Monitor.TryEnter(o, timeout)) { // Failed to acquire lock. #if DEBUG GC.SuppressFinalize(tl.leakDetector); throw new LockTimeoutException(o); #else throw new LockTimeoutException(); #endif } return tl; }