Beispiel #1
0
        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();
            }
        }
Beispiel #2
0
        // 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();
            }
        }
Beispiel #3
0
        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;
        }
Beispiel #4
0
        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();
                }
            }
        }
Beispiel #5
0
 public bool Lock(string operationName)
 {
     return(_lock.Lock(operationName));
 }