コード例 #1
0
        public static async Task RunAsync(
            Func <Task> runFunc,
            DistributedLockOptions options,
            ILogger logger)
        {
            var distributedLock = new DistributedLock <T>(options, logger);

            var acquiredLock = false;

            try
            {
                logger.LogInformation("Trying to acquire lock.");
                acquiredLock = distributedLock.AcquireLock();

                if (!acquiredLock)
                {
                    logger.LogInformation("Could not get lock, another instance is busy.");
                    return;
                }

                await runFunc();
            }
            catch (Exception e)
            {
                logger.LogCritical(0, e, "Encountered a fatal exception, exiting program.");
                throw;
            }
            finally
            {
                if (acquiredLock)
                {
                    distributedLock.ReleaseLock();
                }
            }
        }
コード例 #2
0
 public static void Run(
     Action runFunc,
     DistributedLockOptions options,
     ILogger logger)
 {
     RunAsync(() =>
     {
         runFunc();
         return(Task.CompletedTask);
     }, options, logger).GetAwaiter().GetResult();
 }
コード例 #3
0
        public DistributedLock(DistributedLockOptions options)
        {
            _options = options;

            _lockName = typeof(T).FullName ?? Guid.NewGuid().ToString("N");

            _mutex = new DynamoDBMutex(
                new AmazonDynamoDBClient(
                    options.AwsAccessKeyId,
                    options.AwsSecretAccessKey,
                    options.Region),
                new DynamoDBMutexSettings
            {
                CreateTableIfNotExists = true,
                TableName = options.TableName
            });

            _renewLeaseTimer.Interval = options.LeasePeriod.TotalMilliseconds / 2;
            _renewLeaseTimer.Elapsed += (sender, args) => RenewLease();
        }