繁体   English   中英

Xamarin iOS运行任务,同步返回值

[英]Xamarin iOS Run Task with return value synchronously

我有一个非异步方法,该方法应调用显示UIAlertView的异步方法。 如果单击了Button,则此异步方法将返回一个int。

    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;
    }

如果我从async方法调用此方法,则效果很好,但问题是我有一个绝对不能转换为async的sync方法,因此我需要以同步方式调用此方法并等待响应。 sync方法获得结果后,应继续执行。

我尝试了许多未编译或阻止MainThread且不会显示UIAlertView的解决方案。

也许有人知道我该怎么做,或者也许有一个更好的解决方案。

提前致谢!

可能的解决方案可能是使用ContinueWith。

例如:

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

如果您需要使用当前上下文,则可以扩展ContinueWith方法

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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