/// <summary> /// 安全地对任务进行异步调用。 /// /// 原因:在异步线程中调用任务,如果出现异常,往往会使整个应用程序死机。 /// </summary> /// <param name="action"></param> /// <param name="errorHandler"></param> public static void InvokeSafe(Action action, Action<Exception> errorHandler = null) { action = action.WrapByCurrentPrinciple(); ThreadPool.QueueUserWorkItem(o => { try { action(); } catch (Exception ex) { if (errorHandler != null) { try { errorHandler(ex); } catch { //错误处理再发生异常时,将会被忽略。 } } else { Logger.LogError("异步线程在 SafeInvoke 时发生异常", ex); } } }); }
public void Execute(Action action) { AutoResetEvent autoResetEvent = new AutoResetEvent(false); lock (this) { this._events.Enqueue(autoResetEvent); } action = action.WrapByCurrentPrinciple(); //在后台线程中,执行这个操作 ThreadPool.QueueUserWorkItem(o => { //执行Action action(); autoResetEvent.Set(); }); this.Start(); }
/// <summary> /// 构造一个对应指定方法的预加载器。 /// </summary> /// <param name="loadAction"> /// 真正的加载方法,比较耗时的操作。 /// </param> public ForeAsyncLoader(Action loadAction) { Debug.Assert(loadAction != null, "loadAction != null"); this._action = loadAction.WrapByCurrentPrinciple(); }
/// <summary> /// 对任务进行异步调用。 /// </summary> /// <param name="action"></param> public static void Invoke(Action action) { action = action.WrapByCurrentPrinciple(); ThreadPool.QueueUserWorkItem(o => action()); }