I usually use Task.Run(async....
Is there a way I can do a Xamarin ContentPage Async OnCreate method?
Hi, I dynamically create the pages using the constructor of the ContentPage rather than using xaml. As part of this I sometimes need to call async methods which obviously doesn't follow the "Async all the way" theory as the constructor cannot be async.
So effectively what I want to do is an async OnCreate() method (OnAppearing doesn't work as I have to be able to navigate away and back again without recreating the screen) but content pages don't appear to have that method.
If I then call an async method in the constructor I either need to .Wait() it which freezes the UIThread which is bad, the alternative is to have it just 'fire and forget' which doesn't really work as the page will initialise before I have refreshed the data.
Am I missing something?
2 answers
Sort by: Most helpful
-
-
JessieZhang-MSFT 7,711 Reputation points Microsoft Vendor
2021-04-15T03:13:22.96+00:00 Hello,
Welcome to Microsoft Q&A!
It is recommended you could read through document: https://learn.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap .
Specifically: https://learn.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern .
So we should void calling
.Wait()
or.Result
, as this is going to lock our app.And we don't recommend spin up a new Task either, just call the
ContinueWith
, but realize that your page may be done, so check your state:CallAPIAsync().ContinueWith( t => { if (t.IsFaulted) Log(t.Exception); });
Refer :https://forums.xamarin.com/discussion/28983/call-async-method-in-constructor .
There are some similar threads about this, you can check it here :
https://forums.xamarin.com/discussion/101236/best-practices-execute-method-async-in-viewmodel.https://stackoverflow.com/questions/29054202/how-can-i-call-async-method-from-constructor
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.