示例代码:
PT_USER_INFO user = new PT_USER_INFO(); IList<TES_COMBAT_TASK> taskList = new List<TES_COMBAT_TASK>(); BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += (s, e) => { user = HI.Get<Cache.ICacheService>().UserCache.GetCurrentUserInfo(); taskList = HI.Get<ITaskService>().GetCombatTaskByUserIDUnfinished(user.ID.ToString()); }; worker.RunWorkerCompleted += (s, e) => { try { taskListView.ItemsSource = taskList; } catch { } }; worker.RunWorkerAsync();
BackgroundWorker封装:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; /** * 使用方法: BackWork.Run(() => //DoWork { }, () => //RunWorkerCompleted { }, (ex) => //错误处理 { }); */ namespace Utils { /// <summary> /// BackgroundWorker封装 /// 用于简化代码 /// </summary> public class BackWork { /// <summary> /// 执行 /// </summary> /// <param name="doWork">DoWork</param> /// <param name="workCompleted">RunWorkerCompleted</param> /// <param name="errorAction">错误处理</param> public static void Run(Action doWork, Action workCompleted, Action<Exception> errorAction) { bool isDoWorkError = false; Exception doWorkException = null; BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += (s, e) => { try { if (doWork != null) doWork(); } catch (Exception ex) { isDoWorkError = true; doWorkException = ex; } }; worker.RunWorkerCompleted += (s, e) => { if (!isDoWorkError) { try { if (workCompleted != null) workCompleted(); } catch (Exception ex) { if (errorAction != null) errorAction(ex); } } else { if (errorAction != null) errorAction(doWorkException); } }; worker.RunWorkerAsync(); } } }