在UWP中如何从同步函数显示消息框(即不是异步)

时间:2018-05-04 15:35:42

标签: c# uwp

有没有办法包装UWP异步函数来创建对话框,以便可以从没有async关键字的普通方法调用它们?例如:

var msgbox = new ContentDialog
             {
                   Title   = "Error",
                   Content = "Already at the top of the stack",
                   CloseButtonText = "OK"
             };
             await msgbox.ShowAsync();

3 个答案:

答案 0 :(得分:1)

不,目前无法做到这一点。如果您试图阻止等待对话框关闭,您的应用程序将会死锁。

答案 1 :(得分:0)

public Task<ContentDialogResult> MsgBox(string title, string content)
{
    Task<ContentDialogResult> X = null;

    var msgbox = new ContentDialog
    {
        Title = title,
        Content = content,
        CloseButtonText = "OK"
    };

    try
    {
        X = msgbox.ShowAsync().AsTask<ContentDialogResult>();
        return X;
    }
    catch { 
        return null;
    }
}

private void B1BtnBack_Click(object sender, RoutedEventArgs e)
{
    MsgBox("Beep", "Already at the top of stack");
    return; 

    // ^^^ Careful here. MsgBox returns with an active task
    // running to display dialog box.  This works because
    // the next statement is a return that directly 
    // returns to the UI message loop.  And the 
    // ContentDialog is modal meaning it disables 
    // the page until ok is clicked in the dialog box.
}

答案 2 :(得分:0)

以下是我的工作方式(我在刚刚介绍UWP时的一些现场演示中看到了这一点):

var msgbox = new ContentDialog
             {
                   Title   = "Error",
                   Content = "Already at the top of the stack",
                   CloseButtonText = "OK"
             };
             var ignored = msgbox.ShowAsync();

这在非异步void方法中按预期工作。