Ejemplo n.º 1
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation($"{_serviceName} is starting.");

                _timer = new Timer(_ =>
                {
                    using (LogHelper.AddRequestId())
                    {
                        try
                        {
                            using (var scope = _services.CreateScope())
                            {
                                _logger.LogInformation($"{_serviceName} start working.");
                                scope.ServiceProvider.GetService <T>().Action(cancellationToken).Wait(cancellationToken);
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, $"Unhandled exception in {_serviceName} periodical work");
                        }
                    }
                }, null, TimeSpan.Zero, _duration);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Unhandled exception on initialization in {_serviceName}", ex);
            }
            return(Task.CompletedTask);
        }
Ejemplo n.º 2
0
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Queued Hosted Service is starting.");

            await new [] { TaskQueueLevel.Low, TaskQueueLevel.Medium, TaskQueueLevel.High }.AsyncForeach(async prior =>
            {
                _logger.LogInformation($"Queue #{prior} is starting");
                while (!cancellationToken.IsCancellationRequested)
                {
                    using (LogHelper.AddRequestId())
                    {
                        var(name, workItem) = await _taskManager.DequeueAsync(cancellationToken, prior);

                        _logger.LogDebug($"Queue #{prior}: Start processing work item {name}");

                        try
                        {
                            await workItem(cancellationToken);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex,
                                             $"Queue #{prior}: Error occurred executing {nameof(workItem)}.");
                        }
                    }
                }
            });

            _logger.LogInformation("Queued Hosted Service is stopping.");
        }