Search code examples
c#async-awaitdisplayalert

Net 7 - How to get async function (which is called inside sync function) block the code execution until its done


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();

Solution

  • 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.