在这段代码中,我们模拟WPF中DispatcherObject的两个方法CheckAccess和VerifyAccess对线程模型进行了重新处理,增强了系统的稳定性。在实际工作中,我们也可以提取这两个方法为扩展方法,以便项目中的所有UI类型都能使用到。
WPF支持这两个方法,其全部代码如下所示(注意查看While循环部分):
private void buttonStart_Click(object sender, RoutedEventArgs e)
{
Task t = new Task(() =>
{
while (true)
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
textBlock1.Text = DateTime.Now.ToString();
}));
Thread.Sleep(1000);
}
});
//为了捕获异常,启动了一个新任务
t.ContinueWith((task) =>
{
try
{
task.Wait();
}
catch (AggregateException ex)
{
foreach (Exception inner in ex.InnerExceptions)
{
MessageBox.Show(string.Format("异常类型:{0}{1}来自:
{2}{3}异常内容:{4}", inner.GetType(), Environment.NewLine,
inner.Source, Environment.NewLine, inner.Message));
}
}
}, TaskContinuationOptions.OnlyOnFaulted);
t.Start();
} |
注意:为了演示方便,本建议中的异常没有传递到主线程。在实际编码中,应当始终考虑将异常包装到主线程。
相关链接:
连载1 连载2 连载3 连载4 连载5 连载6 连载7 连载8 连载9
连载10 连载11 连载12 连载13 连载14 连载15 连载71 连载72 连载73
连载74 连载75 连载76 连载77 连载78 连载79 连载80 连载81 连载82
连载83 连载84 连载85 连载86
【福利】填问卷 送2019精选测试大礼包+接口测试实战课程!