示例#1
0
        public static void ReportUnhandledTaskException(Exception exception, object task,
                                                        ITaskExceptionHandler taskExceptionHandler, IServiceProvider serviceProvider, ILogger logger)
        {
            if (exception == null)
            {
                // There was no exception to report
                return;
            }

            var context = new UnhandledTaskExceptionContext(exception, serviceProvider);

            if (task is ITaskExceptionHandler queueableTaskExceptionHandler)
            {
                // The task implements an exception handler, we will let it handle the exception by itself
                queueableTaskExceptionHandler.OnUnhandledException(context);
            }

            // Determine if the task handled the exception
            if (context.IsHandled)
            {
                return;
            }

            // The task did not handle the exception, we will notify the global exception handler
            taskExceptionHandler?.OnUnhandledException(context);
            if (context.IsHandled)
            {
                // The exception was handled by the global handler
                return;
            }

            // Log the unhandled exception
            logger.LogError(exception, "An unhandled exception has occurred while executing the task.");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TaskScheduleHostedService"/> class.
        /// </summary>
        /// <param name="serviceScopeFactory"></param>
        /// <param name="taskSchedulerService"></param>
        /// <param name="taskExceptionHandler"></param>
        /// <param name="logger"></param>
        public TaskScheduleHostedService(
            [NotNull] IServiceScopeFactory serviceScopeFactory,
            [NotNull] ITaskSchedulerService taskSchedulerService,
            [NotNull] ITaskExceptionHandler taskExceptionHandler,
            [NotNull] ILogger <TaskScheduleHostedService> logger)
        {
            Check.NotNull(serviceScopeFactory, nameof(serviceScopeFactory));
            Check.NotNull(taskSchedulerService, nameof(taskSchedulerService));
            Check.NotNull(taskExceptionHandler, nameof(taskExceptionHandler));
            Check.NotNull(logger, nameof(logger));

            _serviceScopeFactory  = serviceScopeFactory;
            _taskSchedulerService = taskSchedulerService;
            _taskExceptionHandler = taskExceptionHandler;
            _logger = logger;
        }