什么时候应该使用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;
}