protected override async Task ExecuteAsync(CancellationToken cancellationToken) { m_logger.LogInformation("Project import background service started."); while (!cancellationToken.IsCancellationRequested) { var externalRepositories = await m_importManager.GetExternalRepositories(cancellationToken); var importTasks = new List <Task>(); try { using (var scope = m_serviceProvider.CreateScope()) { var importPipelineManager = scope.ServiceProvider.GetRequiredService <ImportPipelineManager>(); foreach (var externalRepositoryId in externalRepositories) { var cts = new CancellationTokenSource(); m_importManager.CancellationTokens.TryAdd(externalRepositoryId, cts); importTasks.Add(importPipelineManager.ImportAsync(externalRepositoryId, cts.Token)); } await Task.WhenAll(importTasks); } } catch (OperationCanceledException e) { if (m_logger.IsErrorEnabled()) { m_logger.LogError(e, e.Message); } } catch (AggregateException e) { if (m_logger.IsErrorEnabled()) { m_logger.LogError(e, e.Message); m_logger.LogDebug("Separate exceptions:"); foreach (var exception in e.InnerExceptions) { m_logger.LogError(exception, exception.Message); } } } catch (Exception e) { if (m_logger.IsErrorEnabled()) { m_logger.LogError(e, "Unknown error occured in BackgroundService"); } throw; } finally { foreach (var cancellationTokenSource in m_importManager.CancellationTokens) { cancellationTokenSource.Value.Cancel(); } m_importManager.IsImportRunning = false; } } m_logger.LogInformation("Project import background service stopped."); }