result from Await DisplayAlert Xamarin.Forms

Viewed 1750

Xamarin has awaitable DisplayAlert method which returns Task<bool>.

I have static class Helpers where i want to write code like this:

public static bool DisplayAlert(string title, string message, string accept, string cancel){
    //return answer from Page.DisplayAlert(title, message, accept, cancel);
}

This method will be called from other parts of the app like:

public ... SomeMethod(){
    // some code
    bool result = DisplayAlert(...);
    // some code
}

I want to avoid async/await in SomeMethod. (How you can wait a response from a user asynchronously?!!!!!!)

I tried await Page.DisplayAlert(...), task.Wait() and another. But Task was executed asynchronously with no return value. Or application freezes forever without displaying DisplayAlert.

How to do it? What's the best practice?

1 Answers

If you want SomeMethod to remain Synchronous, this is one option:

public async static Task<bool> DisplayAlert(string title, string message, string accept, 
string cancel){
 return await Page.DisplayAlert(title, message, accept, cancel);
}

// SomeMethod will run Synchronously
public boolean SomeMethod(){
  bool result = StaticClass.DisplayAlert(..).Result;
  return result;
}

EDIT: Fixed some syntax

Related