wpf - 运行长任务而不卡住UI

标签 wpf task microsoft-metro

我正在尝试在后台执行操作,而不卡住UI。

当然,我可以为此使用BackgroundWorker。

但是,我只想使用Task API来做到这一点。

我试过了:

async void OnTestLoaded(object sender, RoutedEventArgs e)
{
   await LongOperation();
}
// It freezes the UI


async void OnTestLoaded(object sender, RoutedEventArgs e)
{
   var task = Task.Run(()=> LongOperation());
   task.Wait();
}


// It freezes the UI

那我应该回到BackgroundWorker吗?还是仅使用任务有解决方案?

最佳答案

你很亲密。

async void OnTestLoaded(object sender, RoutedEventArgs e)
{
  await Task.Run(() => LongOperation());
}
async does not execute a method on a thread pool thread
Task.Run在线程池线程上执行操作,并返回代表该操作的Task

如果在Task.Wait方法中使用async,则为doing it wrong。您应该在await方法中使用async任务,切勿阻塞它们。

关于wpf - 运行长任务而不卡住UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10065000/

相关文章:

c# - 创建大量任务/线程并等待它们全部完成

c# - Metro Style 应用程序的颜色选择器?

c# - 如何防止加载 WPF 应用程序?

c# - 标签 MVVM 中显示的 WPF 百分比状态

c# - 延迟并唤醒正在执行的任务? (任务。延迟?)

返回值的 C# 任务

javascript - 消息对话框中的用户输入

c# - SQLite 中为 String 分配了多少空间?

c# - MVVM SelectedItem.Property OnChanged MVVM SelectedItem.Property OnChanged

c# - 如何有条件地绑定(bind)数据?