简体   繁体   中英

Xamarin iOS Run Task with return value synchronously

I've got a non async method which should call a async method that displays an UIAlertView. This async method returns an int if a Button was clicked.

    public Task<int> ShowAlertAsync(string title, string message, params string[] buttons)
    {
        var tcs = new TaskCompletionSource<int>();

        var alert = new UIAlertView
        {
            Title = title,
            Message = message
        };

        if (buttons.Length > 0)
        {
            foreach (var button in buttons)
            {
                alert.AddButton(button);
            }
        }
        else
        {
            alert.AddButton("OK");
        }

        alert.Clicked += (s, e) => { tcs.TrySetResult((int)e.ButtonIndex); };
        alert.Show();

        return tcs.Task;
    }

this works fine if I call this from an async method, but the problem is that I've got a sync method that definitely can't be converted to async, so I need to call this method in a synchronous way and wait for the response. After the sync method gets the result, it should continue it's execution.

I tried many solutions which all didn't compile or blocked the MainThread and the UIAlertView won't be displayed.

Maybe someone knows how I can do this, or maybe there is a better solution for this.

Thanks in advance!

Possible solution might be to use ContinueWith.

For example:

ShowAlertAsyc("title","message",...).ContinueWith(t=>
{
    //t.Result contains the return value
});

If you need to use the current context than you can extend the ContinueWith method

ShowAlertAsyc("title","message",...).ContinueWith(t=>
{
    //t.Result contains the return value
}, TaskScheduler.FromCurrentSynchronizationContext());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM