在不冻结 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.