Example #1
0
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation($"Starting background service {GetType().FullName}...");

            // Run another task to avoid deadlocks
            return(Task.Run(async() =>
            {
                try
                {
                    Lock = await _distributedLockManager.Acquire(_distributedLockSettings, stoppingToken);

                    _logger.LogInformation($"Lock acquired, executing background service {GetType().FullName}.");

                    await ExecuteLockedAsync(stoppingToken);
                }
                catch (TaskCanceledException)
                {
                    // Don't log exception that is fired by the cancellation token.
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"Background service '{GetType().FullName}' failed.");
                }
                finally
                {
                    if (Lock != null)
                    {
                        await Lock.Release();
                    }
                }
            }));
        }
Example #2
0
        /// <summary>
        /// Ensures that the lock is still valid, otherwise tries to re-acquire it.
        /// </summary>
        /// <returns></returns>
        public async Task Renew(CancellationToken cancellationToken = default)
        {
            if (Status == DistributedLockStatus.Released)
            {
                throw new InvalidOperationException("This lock was explicitly released and cannot be renewed.");
            }

            await CheckIsStillLocked();

            if (Status == DistributedLockStatus.Acquired)
            {
                await _lockManager.SendHeartbeat(_settings);
            }
            else
            {
                await _lockManager.Acquire(_settings, cancellationToken);

                Status = DistributedLockStatus.Acquired;
            }
        }