简体   繁体   English

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

[英]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. 我有一个非异步方法,该方法应调用显示UIAlertView的异步方法。 This async method returns an int if a Button was clicked. 如果单击了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;
    }

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. 如果我从async方法调用此方法,则效果很好,但问题是我有一个绝对不能转换为async的sync方法,因此我需要以同步方式调用此方法并等待响应。 After the sync method gets the result, it should continue it's execution. sync方法获得结果后,应继续执行。

I tried many solutions which all didn't compile or blocked the MainThread and the UIAlertView won't be displayed. 我尝试了许多未编译或阻止MainThread且不会显示UIAlertView的解决方案。

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. 可能的解决方案可能是使用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 如果您需要使用当前上下文,则可以扩展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