/// <summary> /// 添加处理任务对象,同时指定异常处理 /// </summary> /// <param name="taskItem">目标执行委托</param> /// <param name="context">执行上下文参数</param> /// <param name="excetionHandlerTargetType">异常处理类型(必须继承实现TaskExceptionHandler)</param> /// <param name="backAction">回调方法</param> public void AddTaskItem(Action <T> taskItem, T context, Type excetionHandlerTargetType, WaitCallback backAction = null) { HandlerItem <T> item = new HandlerItem <T>(); item.contextObj = context; item.taskItemObj = taskItem; item.backAction = backAction; if (excetionHandlerTargetType != null) { item.exceptionHandlerTarget = excetionHandlerTargetType.FullName; item.exceptionHandlerTargetType = excetionHandlerTargetType; } AddTaskItem(item); }
/// <summary> /// 具体处理对象 /// </summary> public override void Handler() { if (!isStart) { isStart = true;//同一时间只能开启一个线程处理 Thread thread = new Thread(() => { while (isStart) { try { //停留5秒后判断是否有未处理,如果没有直接停掉当前线程 if (!exceptionQueue.Any()) { Thread.Sleep(5000); } if (!exceptionQueue.Any()) { isStart = false;//当前处理完成后停止当前线程 Thread.CurrentThread.DisableComObjectEagerCleanup(); return; } HandlerItem <T> hadlerItem = null; lock (obj) { hadlerItem = exceptionQueue.Dequeue(); } hadlerItem.taskItemObj(hadlerItem.contextObj); } catch (Exception ex) { //待处理 } } }); thread.Start(); thread.IsBackground = true; } }
/// <summary> /// 开启异常处理 /// </summary> public static void StartExceptionHandler(HandlerItem <T> item) { TaskExceptionHandler <T> handlerObj = null; if (item.exceptionHandlerTarget == "Default") { handlerObj = new DefaultExceptionHandler <T>(); } else { try { handlerObj = (TaskExceptionHandler <T>)Activator.CreateInstance(item.exceptionHandlerTargetType); } catch { handlerObj = new DefaultExceptionHandler <T>(); } } handlerObj.AddExceptionTaskItem(item); handlerObj.Handler(); }
/// <summary> /// 添加异常任务项 /// </summary> /// <param name="item"></param> public abstract void AddExceptionTaskItem(HandlerItem <T> item);
/// <summary> /// 设置工作任务和上下文数据 /// </summary> /// <param name="action"></param> /// <param name="contextObj"></param> public void SetWorkTask(HandlerItem <T> contextObj) { this.contextObj = contextObj; }