从线程启动时模态弹出窗口失败 - CSharp WPF
为了批量上传许多文件,我有一段 CSharp WPF 代码,它会生成线程以允许并行上传文件。 如果上传发生错误,将使用 MessageBox 弹出一条消息。这很好用。
但最近我们决定自定义 MessageBox 的外观。我发现当使用 ShowDialog() 打开新的自定义 WPF MessageBox 窗口时,会引发错误,指出无法启动 GUI。仅当生成的线程中的代码尝试打开自定义消息窗口时才会发生这种情况 - 当从主线程打开自定义消息框时,我没有看到问题。
我的临时修复是捕获启动自定义对话框时发生的任何错误,并选择调用标准 MessageBox.Show() 来显示消息。那行得通。
我不确定为什么可以使用标准 MessageBox.Show() 但它不适用于自定义窗口。有办法解决这个问题吗?
To batch upload many files, there is one section of CSharp WPF code that I have which spawns threads to allow parallel uploading of files.
If an error occurs with the upload, a message would be popped up using MessageBox. This works fine.
But now recently we've decided to customize the look of the MessageBox. I find when our new custom WPF MessageBox window is opened with ShowDialog() that an error is thrown saying that it isn't possible to launch a GUI. This only happens when code from the spawned thread attempts to open the custom Message window -- I don't see the problem when a custom MessageBox opens from the main thread.
My temporary fix is to catch any errors that occur when the custom dialog is launched and to alternatively call the standard MessageBox.Show() to display the message. That works.
I'm not sure why it's OK to use the standard MessageBox.Show() but it isn't for the custom window. Is there a way to get around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通常(在任何 GUI-API 中)不要从工作线程调用 GUI 函数,也不在 GUI 线程上做繁重的工作。
标准 MessageBox 在工作线程上工作这一事实令人遗憾。
是的,你完全正确。当您的工作线程上发生需要向用户显示的事情时,将通知(信号、事件,无论您的框架如何调用它)发送到 GUI 线程并在那里显示消息。
Generally (in any GUI-API) don't call GUI functions from worker threads and don't do heavy work on GUI threads.
The fact that the standard MessageBox works on a worker thread is sad.
Yes, you are completely right. When on your worker thread somethings happens that needs to be displayed to the user, send a notification (signal, event, whatever your Framework calls it) to the GUI thread and display the message there.