-1

I have the following function:

public bool ShowMessageQuestion(string message)
{
    var _result = Application.Current.MainPage.DisplayAlert("Test", message, "Yes", "No");
    _result.Start();
    return _result.Result;
}

The DisplayAlert is an async function, so when I execute the above code, I get an exception

Start may not be called on a promise-style task

I would like to get the above code stops executing until user selects yes/no option.

Any idea?

I tried also:

var _result = Application.Current.MainPage.DisplayAlert("Test", "Message", "Yes", "No").GetAwaiter().GetResult();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
anon
  • 13
  • 2
  • Not sure if this is useful to you or not https://stackoverflow.com/questions/72429055/how-to-displayalert-in-a-net-maui-viewmodel – Mike Apr 07 '23 at 14:09
  • It's async, So change the type to `Task` and await it. [microsoft docs](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/pop-ups) – JHBonarius Apr 07 '23 at 14:16
  • Does this answer your question? [How to display alert box with Xamarin.Forms for validation?](https://stackoverflow.com/questions/27519721/how-to-display-alert-box-with-xamarin-forms-for-validation) – JHBonarius Apr 07 '23 at 14:20

1 Answers1

0

You have a method defined as a synchronous method and you attempt inside of it to run an asynchronous method and return its result, without waiting for it. To solve this conundrum, you have two options:

Option 1: Synchronize inside the method

public bool ShowMessageQuestion(string message)
{
    var task = Application.Current.MainPage.DisplayAlert("Test", message, "Yes", "No");
    return task.Wait();
}

This is useful if you need the result to process somewhere which makes it necessary to wait for it.

Option 2: Convert your method to async

public Task<bool> ShowMessageQuestion(string message)
{
    var task = await Application.Current.MainPage.DisplayAlert("Test", message, "Yes", "No");
    return await task;
}

If you do not necessarily need to wait for the result, then you can define your method as async and allow simply issuing it whenever its result is not important for the caller.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175