如何在C#中关闭Win Form之前强制关闭另一个Thread的Message Box? [英] How to enforce close Message Box of another Thread's before closing Win Form in C#?

查看:165
本文介绍了如何在C#中关闭Win Form之前强制关闭另一个Thread的Message Box?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经构建了一个小的多线程窗口应用程序,它由单个Win Form组成。除主线程外,我在新线程中显示消息框,我创建该线程以提示执行操作的权限。如果用户选择是,那么它将继续。如果否则会关闭。它工作正常。



但是我在Message Box出现时遇到问题,除非我关闭消息框,否则我无法关闭Winform。但就我而言,它正在发生逆转。即使消息框出现,我也可以关闭胜利而不关闭从创建新线程中提出的消息框。

请指导我们。如何解决这个问题。

I've built one small multi threading windows application which is consist of single Win Form. Other than Main Thread, i'm displaying Message Box in new thread which i have created for prompt the permission to do the action. If user Select "Yes" then it'll continue. if "No" then it will close. It's working fine.

But i have problem in when Message Box appears, I shouldn't get capable to close Winform unless i close the Message Box. But in my case it's happening reversal. Even though Message Box Appeared i can able to close win From without closing Message Box which has raised from Created New Thread.
Please guide us. How make to solve this.

推荐答案

问题是MessageBox是在与主UI不同的线程上创建的 - 所以尽管是Modal,但它不是UI线程的模态 - 它只阻止在新线程上执行。



所以你可以非常愉快地使用UI控件,而MessageBox就在那里 - 这毕竟是点使用单独的线程!麻烦的是,如果你关闭主窗口,线程代码仍在运行...



首先。将线程从Thread类更改为BackgroundWorker - 这样至少如果主窗口关闭且应用程序退出,线程也将被终止 - 标准Thread类实例是独立的,即使应用程序关闭也将继续运行。因此,如果你关闭主表单,至少会关闭消息框并终止线程。



如果你真的想让线程冻结在用户确认消息框之前的主窗口,然后您必须将该线程作为UI来显示MessageBox,并等待UI在继续之前获得用户确认。这是可能的,但比调用MessageBox.Show!
The problem is that the MessageBox is being created on a different thread to the main UI - so despite being Modal, it is't Modal for the UI thread - it only blocks execution on the new thread.

So you can use UI controls perfectly happily while the MessageBox is there - which is after all the point of using separate threads! The trouble is that if you close the main window, the thread code is still running...

Firstly. change the thread from a Thread class to a BackgroundWorker - that way at least if the main window is closed and the application exits, the thread will also be terminated - standard Thread class instances are independent and will continue to run even if the app shuts down. So if you do close your main form, at least the message box will be closed and the thread terminated as well.

If you really want the thread to "freeze" the main window until the message box has been acknowledged by the user, then you will have to have the thread as the UI to display the MessageBox and wait until the UI has had the user acknowledgement before continuing. This is possible, but is rather more involved than just calling MessageBox.Show!


这篇关于如何在C#中关闭Win Form之前强制关闭另一个Thread的Message Box?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆