在WPF应用程序后台执行任务 [英] Execute task in background in WPF application
本文介绍了在WPF应用程序后台执行任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例
私人无效开始(对象发件人,RoutedEventArgs E)
{
INT进度= 0;
为(;;)
{
System.Threading.Thread.Sleep(1);
进步++;
Logger.Info(进度);
}
}
什么是推荐的方法(TAP或TPL或BackgroundWorker的或调度员或其他人)如果我要开始()
- 请不要阻塞UI线程
- 可以提供进度报告。
- 可以取消
- 支持多线程和多核
解决方案
使用.NET 4.5(或.NET 4.0 + 微软.Bcl.Async ),最好的方法是使用任务
基于API和异步/的await
。它允许使用的方便(伪)顺序代码的工作流程,并已结构化异常处理。
例如:
专用异步无效开始(对象发件人,RoutedEventArgs E)
{
试
{
等待Task.Run(()=>
{
INT进度= 0; $ b $对于B- (;)
{
System.Threading.Thread.Sleep(1);
进展++;
Logger.Info(进展);
}
});
}
赶上(异常前)
{
MessageBox.Show(ex.Message);
}
}
更多阅读:
的异步和等待。
<一个HREF =http://blogs.msdn.com/b/pfxteam/archive/2012/04/12/async-await-faq.aspx>异步/等待FAQ 。
Example
private void Start(object sender, RoutedEventArgs e)
{
int progress = 0;
for (;;)
{
System.Threading.Thread.Sleep(1);
progress++;
Logger.Info(progress);
}
}
What is the recommended approach (TAP or TPL or BackgroundWorker or Dispatcher or others) if I want Start()
- do not block ui thread
- can provide progress reporting
- can be cancelled
- support multithread and multicore
解决方案
With .NET 4.5 (or .NET 4.0 + Microsoft.Bcl.Async), the best way is to use Task
-based API and async/await
. It allows to use the convenient (pseudo-)sequential code workflow and have structured exception handling.
Example:
private async void Start(object sender, RoutedEventArgs e)
{
try
{
await Task.Run(() =>
{
int progress = 0;
for (; ; )
{
System.Threading.Thread.Sleep(1);
progress++;
Logger.Info(progress);
}
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
More reading:
Async in 4.5: Enabling Progress and Cancellation in Async APIs.
这篇关于在WPF应用程序后台执行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文