【问题标题】:result from Await DisplayAlert Xamarin.Forms结果来自等待 DisplayAlert Xamarin.Forms
【发布时间】:2020-03-20 21:18:13
【问题描述】:

Xamarin 具有可等待的 DisplayAlert 方法,该方法返回 Task<bool>

我有staticHelpers 我想写这样的代码:

public static bool DisplayAlert(string title, string message, string accept, string cancel){
    //return answer from Page.DisplayAlert(title, message, accept, cancel);
}

此方法将从应用程序的其他部分调用,例如:

public ... SomeMethod(){
    // some code
    bool result = DisplayAlert(...);
    // some code
}

我想在SomeMethod 中避开async/await。 (如何异步等待用户的响应?!!!!!!)

我试过await Page.DisplayAlert(...)task.Wait() 和另一个。但是Task 是异步执行的,没有返回值。或者应用程序永远冻结而不显示DisplayAlert

怎么做?最佳做法是什么?

【问题讨论】:

    标签: c# xamarin xamarin.forms


    【解决方案1】:

    如果您希望 SomeMethod 保持同步,这是一种选择:

    public async static Task<bool> DisplayAlert(string title, string message, string accept, 
    string cancel){
     return await Page.DisplayAlert(title, message, accept, cancel);
    }
    
    // SomeMethod will run Synchronously
    public boolean SomeMethod(){
      bool result = StaticClass.DisplayAlert(..).Result;
      return result;
    }
    

    编辑:修正了一些语法

    【讨论】:

    • 谢谢,但是这段代码会死锁(((一直使用异步对我来说似乎不合逻辑......
    • 不是死锁,它会同步等待,直到 DisplayAlert 返回结果。这不是死锁的定义。
    • 我试过了,但是出现了死锁。 link
    • 好吧好吧,那你为什么要SomeMethod同步呢?
    • 在移动世界中,您很少需要同步呼叫,在任何情况下都不应阻止您的 UI
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2021-04-22
    • 2014-06-24
    • 1970-01-01
    • 2018-01-03
    相关资源
    最近更新 更多