Maui- app.cs write in constructor http call

Dani_S 4,501 Reputation points
2023-10-01T06:25:22.0666667+00:00

Hi,

I need to write http call asynchronously and i have only constructor their.

Is not allowed to make asynchronous call in constructor?

Thanks,

Developer technologies .NET .NET MAUI
0 comments No comments
{count} votes

Accepted answer
  1. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 36,436 Reputation points Microsoft External Staff
    2023-10-02T04:26:37.4566667+00:00

    Hello,

    Is not allowed to make asynchronous call in constructor?

    It's not allowed.

    You have a http call, and you might have to send an HTTP request as an asynchronous operation, then receive the response by using async and await.

    app constructor is not an async method, and the 'await' operator can only be used within an async method, so it's not allowed.

    It's suggested that you make the asynchronous call in App's lifecycle events, Page.OnAppearing Method, or VisualElement.Loaded Event.

    Update

    I can't make the asynchronous call in App's lifecycle events, Page.OnAppearing Method, So i will make synchronous in app ctor?

    Yes, you could try. But I'm not sure how large the synchronous task would be, the risk of blocking UI thread is high. app constructor runs before app launch, your app might be blank for a while.

    Best Regards,

    Wenyan Zhang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    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.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.