在不冻结 UI 的情况下运行长任务 [英] Running long tasks without freezing the UI

查看:37
本文介绍了在不冻结 UI 的情况下运行长任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在后台执行操作,而不会冻结 UI.

I am trying to perform an action in the background, without freezing the UI.

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

Of course, I could use BackgroundWorker for this.

但是,我只想使用 Task API 来完成.

However, I'd like to do it with the Task API only.

我试过了:

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吗?或者是否有仅使用 Tasks 的解决方案?

So should I go back to BackgroundWorker? Or is there a solution using Tasks only?

推荐答案

你们已经很接近了.

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

async 不在线程池线程上执行方法.

Task.Run 在线程池线程上执行一个操作,并返回一个表示该操作的 Task.

Task.Run executes an operation on a thread pool thread and returns a Task representing that operation.

如果您在 async 方法中使用 Task.Wait,则您是 做错了.你应该在 async 方法中await 任务,不要阻塞它们.

If you use Task.Wait in an async method, you're doing it wrong. You should await tasks in async methods, never block on them.

这篇关于在不冻结 UI 的情况下运行长任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆