gpt4 book ai didi

c# - Xamarin iOS 同步运行具有返回值的任务

转载 作者:行者123 更新时间:2023-11-29 00:29:04 24 4
gpt4 key购买 nike

我有一个非异步方法,它应该调用显示 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;
}

如果我从异步方法调用它,效果很好,但问题是我有一个绝对无法转换为异步的同步方法,所以我需要以同步方式调用这个方法并等待对于响应。同步方法获得结果后,它应该继续执行。

我尝试了很多解决方案,但都没有编译或阻塞主线程,并且 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());

关于c# - Xamarin iOS 同步运行具有返回值的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42342829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com