【问题标题】:`await DisplayAlert` not blocking code in Xamarin.Forms`await DisplayAlert` 不会阻止 Xamarin.Forms 中的代码
【发布时间】:2021-07-15 16:00:03
【问题描述】:

我对@9​​87654323@ 和await 比较陌生,所以我目前不知道哪里出了问题或该怎么做,但我的目标是等待DisplayAlert 对话框首先关闭(通过在继续执行下一行代码之前按下一个按钮)。我已经尝试了下面的两个代码,但都没有帮助。

代码块 A: 显示 DisplayAlert,但不阻止代码执行。

protected override async void OnDisappearing()
{
    if (!Global.EthernetWiring.IsFinished)
    {
        var operation = await DisplayAlert("Verify Action", "Are you sure you want to leave this page? Doing so will forfeit your exercise.", "Yes", "No");

        if (!operation)
        {
            return;
        }
    }

    Global.EthernetWiring.IsT568A = true;
    base.OnDisappearing();
}

代码块 B: 不显示 DisplayAlert 并且不阻止代码执行。

protected override async void OnDisappearing()
{
    await Task.Run(() =>
    {
        if (!Global.EthernetWiring.IsFinished)
        {
            var operation = DisplayAlert("Verify Action", "Are you sure you want to leave this page? Doing so will forfeit your exercise.", "Yes", "No").Result;

            if (!operation)
            {
                return;
            }
        }

        Global.EthernetWiring.IsT568A = true;
        base.OnDisappearing();
    });
}

PS:请不要问关于不使用 MVVM 和其他常见做法的问题。对于一个项目,我的时间线很短,而且范围相当大,我无法及时了解它们。谢谢。

【问题讨论】:

  • “不阻止代码执行”是什么意思。当然,异步方法不会阻塞,但只有在用户选择了他们的选择后才能到达下一行。
  • 从记忆中,一旦你在OnDisappearing,选择是否离开页面已经太迟了,已经发生了。
  • @KlausGütter 这就是我理解它也应该起作用的方式。但是由于某种原因,它不会在警报仍然打开时执行下一行代码。有关Code Block A 的参考,请参见 gif 截图:i.imgur.com/OnG1ebo.gif
  • @DavidG 显然,它不仅限于OnDisappearing 方法。其他常见的用户定义方法也是如此。
  • @Nii 根据您的 gif,您实际上想要阻止使用后退按钮导航,直到用户单击警报操作,对吗?这在共享项目中是不可能的,您需要为 Android 和 iOS 分别执行此操作,例如这里 stackoverflow.com/questions/30657344/… await 不是问题,因为当调用 OnDisappearing 时,您的页面视图已经消失了。此外,当您切换到另一个应用程序或锁定屏幕时,会调用OnDisappearing,因此这可能对您不起作用。

标签: c# android xamarin.forms


【解决方案1】:

我也是 async 和 await 的新手,但我认为如果你从函数中删除 override 它应该可以工作。

如果它不起作用,试试这个:

var operation = DisplayAlert("Verify Action", "Are you sure you want to leave this page? Doing so will forfeit your exercise.", "Yes", "No").GetAwaiter().GetResult()

【讨论】:

  • 即使使用 async 修饰符,它也会阻塞 UI 线程。在Task.Run(() => { ... }); 中运行时,不会出现对话框。
【解决方案2】:

我的目标是等待 DisplayAlert 对话框首先关闭(通过按下按钮),然后再继续执行下一行代码。

你可以试试下面的代码。

 protected async override void OnAppearing()
    {
        base.OnAppearing();
        var Response = await DisplayAlert("Verify Action", "Are you sure you want to leave this page? Doing so will forfeit your exercise.", "Yes", "No");
       
        string Resuming = Response.ToString();
        if (Resuming=="false")
        {
            return;
        }

        Console.WriteLine("this is test!!!!!!");
    }

【讨论】:

    猜你喜欢
    • 2020-10-30
    • 2015-07-07
    • 2018-01-03
    • 2019-08-21
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    相关资源
    最近更新 更多