protected override Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogBackgroundServiceStarting(this); // Run another task to avoid deadlocks return(Task.Factory.StartNew( async() => { try { Lock = await _distributedLockManager.AcquireAsync(_distributedLockSettings, stoppingToken) .ConfigureAwait(false); if (Lock != null) { _logger.LogBackgroundServiceLockAcquired(this); } await ExecuteLockedAsync(stoppingToken).ConfigureAwait(false); } catch (TaskCanceledException) { // Don't log exception that is fired by the cancellation token. } catch (Exception ex) { _logger.LogBackgroundServiceException(this, ex); } finally { if (Lock != null) { await Lock.ReleaseAsync().ConfigureAwait(false); } } }, stoppingToken, TaskCreationOptions.LongRunning, TaskScheduler.Default)); }