async Task in App constructor?

psyonpsyon USMember ✭✭

I need to set MainPage in the app depending on whether or not a settings file exists. The function in PCLStorage to check if a file exists is async though, so I can't call it directly in the App constructor. I tried just firing off a separate task to check if the file exists, and then set MainPage. It works some of the time, but other times, my app gets stuck on the splash screen. I've also tried just setting the MainPage to my main menu in the App constructor, and then firing off the task and changing to the Settings page if the settings file doesn't exist, but then it flashes the main menu first, and switches to settings, and I would prefer it doesn't do that. Is there some method I can use for checking if a file exists while in the App constructor, or a better way choose what I set MainPage too?

Best Answer

Answers

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    @psyon

    What's the actual call you're using? Can't you await the call so execution holds until you get a response?

  • psyonpsyon USMember ✭✭

    I am calling PCLStorage.Current.FileSystem.LocalStorage.CheckExistsAsync(). I can not use await in the App constructor because the constructor is not async. I tried doing CheckExtensionAsync("filename").Wait(), but that causes the error of the app freezing at the splash screen about 50% of the time.

  • psyonpsyon USMember ✭✭

    Sorry, I should correct that, I tried making an async function, that called await on CheckExtensionAsync(), and then I Wait() on that.

  • psyonpsyon USMember ✭✭

    @AlessandroCaliaro said:
    Add a Task.Run async?

    Wouldn't that still just run code asynchronously, and I would have to wait on it?

  • psyonpsyon USMember ✭✭

    Using Task.Run() seems to fix the problem. Why would that work, but calling a method that runs a Task does not?

  • aquabayaquabay AUMember ✭✭

    public App()
    {
    ...
    Task.Run( async () => { await PCLStorage.Current.FileSystem.LocalStorage.CheckExistsAsync(); });
    }

    will ensure execution of main thread will wait until CheckExistsAsync has completed. Read up on how async/await works, it may not be what you think.

Sign In or Register to comment.