Reputation: 2834
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!
Upvotes: 0
Views: 365
Reputation: 2881
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());
Upvotes: 1