c# - 第二个 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
从不显示并且应用程序挂起等待它的答案(我假设)。
如果有人能解释如何解决这个问题,我将不胜感激,但如果他们也能解释为什么会发生这种情况,那就更好了。
解决方案
避免async void
触发和忘记方法,这是命令操作委托将转换为的方法。事件处理程序是一个例外。
创建事件和处理程序
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));
至少现在应该能够捕获任何抛出的异常以了解存在的问题(如果有的话)。
推荐阅读
- r - 替换值多列
- browser - 如果您使用 iframe,浏览器的自动播放策略是基于父站点还是嵌入站点?
- elasticsearch - fluentbit conf 帮助在 k8s 日志中进行堆栈跟踪
- gcc - 如何在 Windows 上使用 gcc -I?
- azure-devops - 我想跟踪我们在 Azure 板上调查工作项目所花费的时间
- html - 角度设置默认数值
- flutter - 在 Flutter 中将颜色从默认更改为自定义以实现暗模式?
- javascript - 如何在没有事件数据的情况下从 JavaScript 使用 dispatchEvent 函数到 Angular 12 应用程序
- kubernetes-helm - OCI 不推荐使用 Helm Chart 导出命令
- node.js - 如何使用 Node JS 提高 MongoDB 的性能?