When should you use Task.Run() rather than await?

五迷三道 提交于 2019-12-20 05:15:28

问题


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

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)

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?

Thanks!


回答1:


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

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).

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;
}



回答2:


I don't think it matters. As far as I know, both methods get dispatched to a thread in the thread pool.

Using async will make the async method run on a background thread and continue on the thread that started it when the async method is finished. You can imagine the compiler seeing the await keyword, put the awaited method in a background thread and wiring up events to notice when the asynch method is finished. Therefore this might be the better choice if you want to show a UI change because of the successful save, and because this is lesser code of course.

Task.Run() would be nicer when you for any reason don't want to put the code in an async method, for example because you want the calling method itself not be async. Also, there's lesser event marshaling involved, but I heavily doubt that there's any performance difference at all.



来源:https://stackoverflow.com/questions/13854720/when-should-you-use-task-run-rather-than-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!