方式一:
Task.Run(() =>
{
var dialogResult= MessageBox.Show("Message", "Title", MessageBoxButtons.OKCancel);
if (dialogResult == System.Windows.Forms.DialogResult.OK)
MessageBox.Show("OK");
else
MessageBox.Show("Cancel");
});
方式二:
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);
}
调用:
ShowMessageBoxAsync($"Error Message:{ex.Message}{Environment.NewLine}Error StackTrace:{ex.StackTrace}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
这篇博客探讨了两种异步显示消息框的方法。方式一是使用Task.Run,方式二是通过委托和BeginInvoke实现。这两种方法允许在后台线程中显示消息框,避免阻塞UI。示例代码展示了如何在不同场景下应用这些技术。
923

被折叠的 条评论
为什么被折叠?



