0

I am using a popup page plugin. It works as below;

var confirm = new AlertDialog(new AlertSettings() { Title = "Confim Title", Message = "Confirm Question?"});
confirm.Callback += (result) =>
{
    if (result)
    {
        //> do something
    }
};

await PopupNavigation.PushAsync(confirm);

I am trying to write a service for getting callback result as bool as following;

  public interface IDialogsService
    {

        Task<bool> DisplayConfirmAsync(string title, string message);

    }

public class DialogsService : IDialogsService
    {

        public DialogsService()
        {

        }

        public async Task<bool> DisplayConfirmAsync(string title, string message)
        {
            bool tresult = false;

            var confirm = new AlertDialog(new AlertSettings() { Title = title, Message = message});


            confirm.Callback += (result) =>
            {

                tresult = (bool)result;

            };

            await PopupNavigation.Instance.PushAsync(confirm);

            return tresult;
        }
    }

I try to run Task for getting result as bool as below;

bool result = await DialogsService.DisplayConfirmAsync("Confim Title", "Confirm Question?");

My question is "above approach is correct or not?" Thank you in advance.

Kerberos
  • 1,228
  • 6
  • 24
  • 48
  • If `Callback` is guaranteed to be called before `PushAsync` returns I think it should work fine. – JonasH Jun 09 '20 at 12:30
  • 2
    Firstly, define "correct" more precisely. Does the code return the data you expected, without crashing? That's one definition of correct. Another definition might concern performance/speed, another might be about adhering to coding standards or other rules. We don't really know what you mean. Can you be more specific? Is the code giving you a problem? – ADyson Jun 09 '20 at 12:30
  • 1
    Having said all that, despite the lack of clarity over what your code is doing right, now, from looking at it I would guess you'll have an issue because the callback will be unlikely to have executed before the DisplayConfirmAsync function has returned. This answer https://stackoverflow.com/a/54130240/5947043 shows a technique to wrap a delegate callback inside a Task so you can use it more easily. It does this by making use of TaskCompletionSource . There's also a very good explanation and example here: https://stackoverflow.com/questions/15316613/when-should-taskcompletionsourcet-be-used – ADyson Jun 09 '20 at 12:38
  • And documentation here: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskcompletionsource-1?view=netcore-3.1 – ADyson Jun 09 '20 at 12:39

0 Answers0