Use await in App()

Jassim Al Rahma 1,616 Reputation points
2022-10-24T21:47:37.643+00:00

Hi,

How can I use the await inside the App() in MAUI like this:

public App()  
{  
	InitializeComponent();  
  
    PermissionStatus status = await Permissions.RequestAsync<Permissions.ContactsRead>();  
  
    if (status == PermissionStatus.Granted)  
    {  
        // do something  
    }  
    else  
    {  
        // do something else  
    }  
}  

Thanks,
Jassim

Developer technologies .NET .NET MAUI
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 36,436 Reputation points Microsoft External Staff
    2022-10-25T08:52:56.343+00:00

    Hello @Jassim Al Rahma ,

    You cannot use await in App(), because the await operator can only be used within an async method, App() is a constructor, async constructors are not allowed. There is a similar question - Run await inside constructor - Microsoft Q&A, you could check it.

    For more details, you can refer to Compiler Error CS4033 | Microsoft Learn
    and Asynchronous programming in C# | Microsoft Learn.

    In addition, you are requesting the Android permissions, you can call it in the OnAppearing method of AppShell or other Pages.

    protected override async void OnAppearing()  
        {  
            base.OnAppearing();  
            PermissionStatus status = await Permissions.RequestAsync<Permissions.ContactsRead>();  
      
            if (status == PermissionStatus.Granted){  
                // do something  
            }else{  
                // do something else  
            }  
        }  
    

    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.

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.