public static async Task <bool> TryLockOperationAsync(this IOperationLock lockObj, Func <Task> operation, TimeSpan timeout) { var interval = TimeSpan.FromMilliseconds(250); var elapsed = TimeSpan.Zero; while (!lockObj.Lock()) { if (elapsed >= timeout) { return(false); } await Task.Delay(_sleepInterval); elapsed += _sleepInterval; } try { await operation(); return(true); } finally { lockObj.Release(); } }
// try acquire lock and then execute the operation // return true if lock acquired and operation executed public static bool TryLockOperation(this IOperationLock lockObj, Action operation, TimeSpan timeout) { var elapsed = TimeSpan.Zero; while (!lockObj.Lock()) { if (elapsed >= timeout) { return(false); } Thread.Sleep(_sleepInterval); elapsed += _sleepInterval; } try { operation(); return(true); } finally { lockObj.Release(); } }
private static async Task<bool> WaitToLockAsync(IOperationLock lockObj, string operationName, TimeSpan timeout) { var elapsed = TimeSpan.Zero; while (!lockObj.Lock(operationName)) { if (elapsed >= timeout) { return false; } await Task.Delay(_sleepInterval); elapsed += _sleepInterval; } return true; }
public static void LockOperation(this IOperationLock lockObj, Action operation, Action onBusy) { bool lockTaken = lockObj.Lock(); if (!lockTaken) { onBusy(); return; } try { operation(); } finally { if (lockTaken) { lockObj.Release(); } } }
public bool Lock(string operationName) { return(_lock.Lock(operationName)); }