/// <summary>
        /// 工作线程周期执行任务。
        /// </summary>
        private async void ThreadWork()
        {
            while (Running)
            {
                // 获取目标任务
                TTask task;
                try
                {
                    task = await GetTaskAsync();
                }
#pragma warning disable CA1031 // Do not catch general exception types
                catch (Exception ex)
                {
                    OnTaskBuildFaulted(new TaskBuildFaultedEventArgs(new BackgroundTaskException("BackgroundTask build faulted.", ex)));
                    // 使用空闲休眠时间休眠
                    TaskWaitHandle.WaitOne(TaskIdleTime);
                    continue;
                }
#pragma warning restore CA1031 // Do not catch general exception types

                if (null == task)
                {
                    // 使用空闲休眠时间休眠
                    TaskWaitHandle.WaitOne(TaskIdleTime);
                    continue;
                }

                // 定义任务执行完成事件参数
                var taskExecutedArgs = new TaskExecutedEventArgs <TTask>(task);

                try
                {
                    OnTaskExecuting(new TaskExecutingEventArgs <TTask>(task));
                    await ExecuteTaskAsync(task);
                }
#pragma warning disable CA1031 // Do not catch general exception types
                catch (Exception ex)
                {
                    taskExecutedArgs.IsFaulted = true;
                    taskExecutedArgs.Exception = new BackgroundTaskException(ex.Message, ex);
                }
#pragma warning restore CA1031 // Do not catch general exception types
                finally
                {
                    // 通知工作线程已执行完一轮任务。
                    taskExecutedArgs.CompletedTime = DateTime.Now;
                    OnTaskExecuted(taskExecutedArgs);
                }

                // 工作线程周期信号量
                TaskWaitHandle.WaitOne(TaskBusyTime);
            }

            TaskWaitHandle.Dispose();
            TaskWaitHandle = null;

            // 通知工作线程已退出。
            OnTaskThreadExited(new TaskThreadExitedEventArgs());
        }
Exemplo n.º 2
0
        /// <summary>
        /// 通知工作线程执行任务完成。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="ObjectDisposedException"></exception>
        protected void OnTaskExecuted(object sender, TaskExecutedEventArgs <TTask> e)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(nameof(BackgroundTaskThreadService <TTask, TThread>));
            }

            DecrementWorkThread();
            TaskExecuted?.Invoke(sender, e);
        }
 /// <summary>
 /// 通知工作线程执行任务完成。
 /// </summary>
 /// <param name="e"></param>
 protected virtual void OnTaskExecuted(TaskExecutedEventArgs <TTask> e)
 {
     TaskExecuted?.Invoke(this, e);
 }