The async/await threading is driving me crazy here. I have done a lot of research on the possibility to do Async initialization.
Here is the problem. I am trying to make my app load into a specific page according to the current apps status. To determine the status of the app. It includes scanning into the Data folder. In order to use the Storage API in UWP. I must create an async dependency service in Xamarin Forms.
I am using a singleton pattern with an AppManager class here.
AppManager.cs
public class AppManager{
public static AppManager Instance = new AppManager();
public List<Jobs> JobList = new List<Jobs>();
public async Task InitializeAsync(){
JobList.AddRange(await DependencyService.Get<IFileService>().GetJobs());
}
public bool JobExists(string jobName){
return JobList.Any(j => j.Name == jobName);
}
}
When the App starts, it will need to load the JobList from the Data folder first. Then look into the JobList and determine which page to go navigate to.
What I am trying to do currently is calling the code below from the constructor of the App class.
App.xaml.cs
InitializeComponent(); // Default
var appManager = AppManager.Instance;
appManager .InitializeAsync();
if(appManager .JobExists("JobA")){
MainPage = new PageA();
}else{
MainPage = new PageB();
}
This will always bring me to PageB as the list is empty because the initialization is not finished. This is caused by running async code in synchronous thread.
I have read about multiple ways to make Async constructors in this blog. However, they still require me to make an await function in the call which is not possible in this case.
I have also tried moving the whole App() constructor code into an async Task function then call InitializeAsync().Wait() in the constructor. However, Xamarin Forms will complain at runtime. As App is having null reference on MainPage.
I would like to know if it is possible to achieve the full initialization using an awaited function without involving bad practices(e.g. async void)? I also have some idea of how to work around for the situation, such as using SystemIO instead of Storage API will still work for Xamarin Forms UWP. But I would really like to go deep into async function instead of just making it work. Thanks.