简体   繁体   English

使用form.ShowDialog()时,mainform中的线程不起作用

[英]When using form.ShowDialog() a thread in mainform doesn't work

I have a form I'm showing using form.showDialog() and in the main form I have a thread that is sending a message every x seconds. 我有一个正在使用form.showDialog()显示的表单,在主表单中,我有一个线程每x秒发送一条消息。 I notice that while I'm in the window that I just opened the new form that I opened using ShowDialog the thread doesn't run. 我注意到当我在窗口中刚刚打开使用ShowDialog打开的新窗体时,该线程无法运行。 How can I make it continue running even when a ShowDialog is used? 即使使用ShowDialog,如何使它继续运行?

Code: 码:

codeshowAllScriptsWindow window = new showAllScriptsWindow(this); 
window.Show();

and in the mainform I have a thread that keeps sending a message but is stopped because of this showdialog. 在主窗体中,我有一个线程不断发送消息,但由于该showdialog而停止了。 Note that when I use show() it doesn't happen. 请注意,当我使用show()时不会发生。

ShowDialog() is a blocking call. ShowDialog()是一个阻止调用。 The thread actually runs, it is busy pumping the message loop for the dialog. 线程实际上在运行,它正忙于为对话框添加消息循环。 This is no different from what happens on the main thread of your program. 这与程序的主线程上没有什么不同。

Doing this is very unwise, the dialog has no Z-order relationship with the rest of the windows in your app. 这样做是非常不明智的,该对话框与应用程序中的其他窗口没有Z顺序关系。 One classic mishap is that it can disappear behind another window but no good way for the user to find it back. 一个经典的不幸事故是它可以消失在另一个窗口后面,但是用户找不到找回它的好方法。 Use Control.BeginInvoke to create the dialog on the UI thread instead. 使用Control.BeginInvoke可以在UI线程上创建对话框。 This also ensures that your thread keeps 'running'. 这还可以确保您的线程保持“运行”状态。

The message pump is "stolen" by your modal dialog you are displaying. 所显示的模式对话框中消息泵被“窃取”。 You have 2 options: 你有2个选择:

  1. Don't use modal dialogs (use formShow()) 不要使用模式对话框(使用formShow())
  2. Use a new thread to do the work and use the main thread for UI. 使用新线程来完成工作,并将主线程用于UI。

Although it seems unrelated at first glance, you might take a look at this question . 尽管乍看起来似乎无关紧要,但是您可以看一下这个问题 The problem you're having is that the form.showDialog() call creates a modal dialog, halting the progression of code on that thread. 您遇到的问题是form.showDialog()调用会创建一个模式对话框,从而停止该线程上的代码进度。 If you spin another thread and fire that call there, your first thread will continue running as the dialog displays. 如果旋转另一个线程并在该位置触发该调用,则第一个线程将继续运行,并显示对话框。

使用System.Threading.Timer而不是System.Windows.Form.Timer。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM