2016-01-17 63 views
0

我的MessageBox是异步的,但是我怎样才能返回DialogResult?C#如何使异步MessageBox返回DialogResult?

这里是我的代码:

class AsyncMessageBox 
{ 
    private delegate void ShowMessageBoxDelegate(string strMessage, string strCaption, MessageBoxButtons enmButton, MessageBoxIcon enmImage); 
    // Method invoked on a separate thread that shows the message box. 
    private static void ShowMessageBox(string strMessage, string strCaption, MessageBoxButtons enmButton, MessageBoxIcon enmImage) 
    { 
     MessageBox.Show(strMessage, strCaption, enmButton, enmImage); 
    } 
    // Shows a message box from a separate worker thread. 
    public void ShowMessageBoxAsync(string strMessage, string strCaption, MessageBoxButtons enmButton, MessageBoxIcon enmImage) 
    { 
     ShowMessageBoxDelegate caller = new ShowMessageBoxDelegate(ShowMessageBox); 
     caller.BeginInvoke(strMessage, strCaption, enmButton, enmImage, null, null); 
    } 
} 
+1

为什么地球上需要异步消息框? – Dennis

+1

虽然我不知道异步消息框的用法,但是如果您想要显示非阻塞消息框并使用dialogresult,则可以使用Task.Run' –

+0

我在线程序中使用了异步消息框。这有助于保持连接活着。例如,如果有人断开连接,它会显示messagebox。如果有人断开连接,则会显示另一个消息框。这很难解释,但我得到了答案。 –

回答

3

如果你想使用非阻塞的消息框的对话结果,并执行基于结果的工作:

Task.Run(() => 
{ 
    var dialogResult= MessageBox.Show("Message", "Title", MessageBoxButtons.OKCancel); 
    if (dialogResult == System.Windows.Forms.DialogResult.OK) 
     MessageBox.Show("OK Clicked"); 
    else 
     MessageBox.Show("Cancel Clicked"); 
}); 

注:

  • Task.Run之后的代码立即运行,而不管消息框如何。
+0

非常感谢! ;) –

+0

欢迎您:) –