Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's difference Task.Run() , Calling async void AAA() on Xamarin forms?

Tags:

c#

wpf

xamarin

task

As far as I know, there are three ways to call async method. (I'm sure there are much more)

  • 1> Task.Run(async () = {...}).
  • 2> Just calling AAA();

and AAA should be looks like

async void AAA()
{
...
}
  • 3> Device.InvokeMainThread(async () => {...});

I know If I use option 1(Task.run) process will go on background thread and option 3 is not.

What about option 2? It's on main thread if I called from OnAppearing()?
First of all, Is there not any problem to use like that?

And option2 and 3 are same?

like image 723
Bright Lee Avatar asked Oct 02 '16 13:10

Bright Lee


People also ask

What is the difference between async void and async task?

A Task returning async method can be awaited, and when the task completes, the continuation of the task is scheduled to run. A void returning async method cannot be awaited; it is a "fire and forget" method. It does work asynchronously, and you have no way of telling when it is done.

What is the difference between task run and async await?

Async methods are intended to be non-blocking operations. An await expression in an async method doesn't block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.

What does async void do?

With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. Figure 2 illustrates that exceptions thrown from async void methods can't be caught naturally.

What is async in xamarin forms?

Android support async and await - this document provides explanations and an example of using the new syntax with Xamarin. Xamarin's Async support is built on the Mono 3.0 foundation and upgrades the API profile from the being a Mobile-friendly version of Silverlight to be a mobile-friendly version of . NET 4.5.


1 Answers

  1. Executes AAA on a thread pool thread.
  2. Executes AAA on the calling thread.
  3. Executes AAA on the main thread.

As an aside, you should avoid async void methods.

like image 65
Charles Mager Avatar answered Dec 07 '22 04:12

Charles Mager