コード例 #1
0
        protected override async Task ExecuteAsync(
            CancellationToken stoppingToken)
        {
            this.logger?.LogInformation("Queued Hosted Service is starting.");

            while (!stoppingToken.IsCancellationRequested)
            {
                var context = await taskQueue.DequeueAsync(stoppingToken);

                try
                {
                    if (context != null)
                    {
                        _ = context.WorkItem(context.CancellationToken, context)
                            .ContinueWith(state =>
                        {
                            taskQueue.CleanUp(context);
                            semaphore.Release();
                            if (state.Exception != null)
                            {
                                this.logger?.LogError(
                                    $"Error occurred executing {nameof(context)}. Ex = {state.Exception}");
                            }
                        }, stoppingToken);

                        await semaphore.WaitAsync(stoppingToken);
                    }
                }
                catch (Exception ex)
                {
                    this.logger?.LogError($"Error occurred executing {nameof(context)}. Ex = {ex.Message}");
                }
            }

            this.logger?.LogInformation("Queued Hosted Service is stopping.");
        }