Razvan Emil
Razvan Emil

Reputation: 585

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

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?

Upvotes: 3

Views: 258

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457057

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:

Upvotes: 4

Related Questions