代码:
using log4net; using SunCreate.CombatPlatform.Security; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Threading; namespace SunCreate.CombatPlatform.Client { /// <summary> /// 线程帮助类(处理单线程任务) /// </summary> public class ThreadHelper { private static ILog _log = log4net.LogManager.GetLogger(typeof(ThreadHelper)); /// <summary> /// 执行 /// 例:ThreadHelper.Run(() => { }, (ex) => { }); /// </summary> /// <param name="doWork">在线程中执行</param> /// <param name="errorAction">错误处理</param> public static System.Threading.Tasks.Task Run(Action doWork, Action<Exception> errorAction = null) { System.Threading.Tasks.Task task = System.Threading.Tasks.Task.Factory.StartNew(() => { try { if (doWork != null) doWork(); } catch (Exception ex) { _log.Error("ThreadHelper.Run 错误", ex); if (!SP.Get<IOnlineService>().GetNetStatus()) { SP.Get<IUIManager>().Dispatcher.BeginInvoke(new Action(() => { TaskDialog.Show("连接数据库失败,请联系系统管理员,给您带来不便,敬请谅解"); })); } else { SP.Get<IUIManager>().Dispatcher.BeginInvoke(new Action(() => { new WaitingWindow("查询失败,请联系系统管理员,给您带来不便,敬请谅解").Show(); })); } if (errorAction != null) errorAction(ex); } }); return task; } /// <summary> /// 封装Dispatcher.BeginInvoke /// 例:ThreadHelper.BeginInvoke(this.Dispatcher, () => { }, (ex) => { }); /// </summary> /// <param name="errorAction">错误处理</param> public static void BeginInvoke(Dispatcher dispatcher, Action action, Action<Exception> errorAction = null) { dispatcher.BeginInvoke(new Action(() => { try { action(); } catch (Exception ex) { _log.Error("ThreadHelper.BeginInvoke 错误", ex); TaskDialog.Show("加载失败,请联系系统管理员,给您带来不便,敬请谅解"); if (errorAction != null) errorAction(ex); } })); } } }