首页 > 解决方案 > 第二个 DisplayAlert 挂起

问题描述

我正在使用 Xamarin Forms 构建应用程序,但我遇到了一次DisplayAlert触发问题,但第二次挂起。

请考虑以下代码:

ThisThingClickedCommand = new Command(
async () =>
{
    var continue = true;
    if (SomeVariable.is_flagged == 0)
    {
        continue = await PageSent.DisplayAlert("User Question", "This is a question for the user", "Yes", "No");
    }

    if (continue)
    {
        Debug.WriteLine("This debug fires");
        var AnswerToSecondQuestion = await PageSent.DisplayAlert("Second Question", "This is a second question for the user", "Yes", "No");
        if (AnswerToSecondQuestion)
        {
            // Do more things
        }
        Debug.WriteLine("This one does not :(");
    }
}),

上面的代码已经在一个项目中存在了很长时间并且似乎一直有效,直到最近更新到 Visual Studio 2017 以及随后的一些新的目标版本的 Windows。

当我在 Windows 上启动应用程序(目前在其他设备上未经测试)并且这段特定的代码运行时,第一个DisplayAlert显示没有问题,但是第二个DisplayAlert从不显示并且应用程序挂起等待它的答案(我假设)。

如果有人能解释如何解决这个问题,我将不胜感激,但如果他们也能解释为什么会发生这种情况,那就更好了。

标签: c#xamarin.formsuwpasync-awaitxamarin.uwp

解决方案


避免async void触发和忘记方法,这是命令操作委托将转换为的方法。事件处理程序是一个例外。

参考Async/Await - 异步编程的最佳实践

创建事件和处理程序

private event EventHandler raiseAlerts = delegate { };
private async void OnRaiseAlerts(object sender, EventArgs args) {
    var _continue = true;
    if (SomeVariable.is_flagged == 0) {
        _continue = await PageSent.DisplayAlert("User Question", "This is a question for the user", "Yes", "No");
    }

    if (_continue) {
        Debug.WriteLine("This debug fires");
        var AnswerToSecondQuestion = await PageSent.DisplayAlert("Second Question", "This is a second question for the user", "Yes", "No");
        if (AnswerToSecondQuestion) {
            // Do more things
        }
        Debug.WriteLine("This one does not :(");
    }
}

订阅活动。很可能在构造函数中

raiseAlerts += OnRaiseAlerts

并在命令动作委托中引发事件

ThisThingClickedCommand = new Command(() => raiseAlerts(this, EventArgs.Empty));

至少现在应该能够捕获任何抛出的异常以了解存在的问题(如果有的话)。


推荐阅读