什么时候应该使用Task.Run()而不是等待? [英] When should you use Task.Run() rather than await?

查看:425
本文介绍了什么时候应该使用Task.Run()而不是等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在存储数据模型的状态.我克隆了数据模型,然后希望将其异步写入磁盘".

I am storing the state of my data model. I clone the data model and then want to have it written to "disk" asynchronously.

我应该使用在后台线程上运行它的Task.Run()吗? 还是我应该使它成为一个异步函数而不等待它? (这将使其在UI线程上运行)

Should I be using Task.Run() which runs it on a background thread? Or should I just make it an async function and not await on it? (this will make it run on the UI thread)

类似的东西,但是我的问题有点不同: 异步任务.使用MVVM运行

Similar stuff to this, but my question is a bit different: async Task.Run with MVVM

决定选择哪个标准是什么?

And what is the criteria to decide which to choose?

谢谢!

推荐答案

对于要在线程池线程上运行的基于CPU的工作,应使用Task.Run.

You should use Task.Run for CPU-based work that you want to run on a thread pool thread.

在您所处的情况下,您希望在不阻止UI的情况下进行基于I/O的工作,因此Task.Run不会给您任何东西(除非您没有可用的异步I/O API).

In your situation, you want to do I/O based work without blocking the UI, so Task.Run won't get you anything (unless you don't have asynchronous I/O APIs available).

作为旁注,您肯定要做await这项工作.这样可以使错误处理更加简洁.

As a side note, you definitely do want to await this work. This makes error handling much cleaner.

所以,这样的话就足够了:

So, something like this should suffice:

async void buttonSaveClick(..)
{
  buttonSave.Enabled = false;

  try
  {
    await myModel.Clone().SaveAsync();
  }
  catch (Exception ex)
  {
    // Display error.
  }

  buttonSave.Enabled = true;
}

这篇关于什么时候应该使用Task.Run()而不是等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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