Xamarin Using async./wait VS await Task.Run (in Xamarin)

拟墨画扇 提交于 2021-02-10 07:04:13

问题


I have been researching about async/await vs await Task.Run but have not found a definite conclusion.

  1. Does "async/await" always run on a separate thread from the UI? And if yes why use "await Task.Run"?

  2. From my research, the recommendation is to use "await Task.Run" for CPU intensive tasks and "await/async" for data transfer scenarios (I/O) but others have recommended using await Task.Run (if needing the return) or just Task.Run (fire and forget) for ANY longer running activities in Xamarin.

So what is the best use for "await Task.Run" especially in the context of Xamarin, in contrast with just async/await?


回答1:


Does "async/await" always run on a separate thread from the UI?

No.

From my research, the recommendation is to use "await Task.Run" for CPU intensive tasks and "await/async" for data transfer scenarios (I/O)

That's a good general guideline for UI applications. Plain async/await doesn't use additional threads; it just keeps your UI responsive. If you have CPU-bound code, then you do need another thread, so you use Task.Run, and you can consume it using await which keeps your UI responsive while a background thread runs the CPU-bound code.

but others have recommended using await Task.Run (if needing the return) or just Task.Run (fire and forget) for ANY longer running activities in Xamarin.

I don't recommend fire-and-forget. Among other issues, it can hide exceptions. I recommend always using await.

So what is the best use for "await Task.Run" especially in the context of Xamarin, in contrast with just async/await?

The general rule above is valid: use async/await for I/O operations, and Task.Run for CPU-bound operations. Every once in a while there's an exception to that rule. E.g., sometimes I/O-bound operations are blocking and they don't provide a fully asynchronous API; in that case, it would be proper use await Task.Run to block a background thread instead of the UI thread even though the operation is technically I/O-bound and not CPU-bound.

Further reading:

  • async best practices
  • Task.Run etiquette
  • Asynchronous MVVM data binding


来源:https://stackoverflow.com/questions/66040144/xamarin-using-async-wait-vs-await-task-run-in-xamarin

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