简体   繁体   English

在后台线程上创建表单并使用Form.ShowDialog

[英]Creating a Form and using Form.ShowDialog on a background thread

Using Winforms, If I'm on a thread that is not the "main" ui thread can I safetly 使用Winforms,如果我在一个不是“主要”ui线程的线程上,我可以安全地使用

  1. Create a Form, 创建表单,
  2. Call ShowDialog on that form 在该表单上调用ShowDialog

It seems like I would be obeying the rule of: Winforms controls must be modified on the thread they were created in. 看起来我会遵守以下规则:必须在创建它们的线程上修改Winforms控件。

From some of the reading I've done it seems like ShowDialog will create its own message pump so that I don't need to worry about the Form being created on a thread that already has a message pump. 从我已经完成的一些阅读中看来,ShowDialog似乎会创建自己的消息泵,这样我就不必担心在已经有消息泵的线程上创建Form。

The background of the question is that I get a callback where I'd like to display some Winforms UI, but I don't have access to any other UI that I could use to Invoke to the main thread. 问题的背景是我得到一个回调,我想显示一些Winforms UI,但我没有访问任何其他可以用来调用主线程的UI。

That's roughly correct, albeit that it is pretty important that you call the thread's SetApartmentState() method to switch the thread to STA. 这大致是正确的,尽管调用线程的SetApartmentState()方法将线程切换到STA非常重要。 Important for many UI operations, including the clipboard, drag and drop and the shell dialogs. 对于许多UI操作很重要,包括剪贴板,拖放和shell对话框。 And that you usually have a crummy Z-order problem when the form that you create on the thread is not in the foreground and hides behind another window. 当你在线程上创建的表单不在前台并隐藏在另一个窗口后面时,你通常会遇到一个糟糕的Z顺序问题。 Or has the nasty habit of actually do move in the foreground when the user doesn't expect it and grab a mouse click or keystroke unexpectedly. 或有实际的坏习惯在前台当移动用户不希望它抢点击鼠标或意外击键。

These are hard problems to fix, they do make your app flaky. 这些都是难以解决的问题,它们会让你的应用变得片状。 There's no good reason to not have a reference to invoke to, you can also pass it to the class some way some how. 没有充分的理由没有引用调用,你也可以通过某种方式将它传递给类。 You've always got Application.OpenForms[0] to fall back on, if really necessary. 如果真的有必要的话,你总是让Application.OpenForms [0]重新开始。

Yes, you can do that, but if you want the dialog to actually act like a modal dialog (ie, block the parent Window, which I assume you want since you are calling ShowDialog ) then be prepared to be disappointed. 是的,您可以这样做,但是如果您希望对话框实际上像一个模态对话框(即阻止父窗口,我假设您想要,因为您调用ShowDialog ),那么请准备好失望。

What problem are you actually trying to solve here. 你真的想在这里解决什么问题。 It sounds like you want a modal dialog that doesn't block, which is a bit strange. 听起来你想要一个不会阻塞的模态对话框,这有点奇怪。 If you explain the problem at hand there may exist a solution you have not yet considered. 如果您解释手头的问题,可能存在您尚未考虑的解决方案。

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

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