3

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
  • Hi, you could have a look at this blog, it will be helpful to understand that. Commented Feb 4, 2021 at 10:00

1 Answer 1

4

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.