不同线程上的新表单
因此,我的应用程序中有一个线程,其目的是侦听来自服务器的消息并根据收到的消息采取行动。
当我想从服务器发出消息时遇到了一个问题,当客户端应用程序收到它时,客户端应用程序将打开一个新表单。然而,这个新形态却立刻冻结了。
我认为发生的情况是,新表单加载在与侦听服务器的线程相同的线程上,当然服务器正忙于侦听流,进而阻塞线程。
通常,对于客户端侦听线程中的其他函数,我会使用调用来更新主窗体的 UI,因此我想我所要求的是是否有一种在主窗体上调用新窗体的方法。
So I have a thread in my application, which purpose is to listen to messages from the server and act according to what it recieves.
I ran into a problem when I wanted to fire off a message from the server, that when the client app recieves it, the client app would open up a new form. However this new form just freezes instantly.
I think what's happening is that the new form is loaded up on the same thread as the thread listening to the server, which of course is busy listening on the stream, in turn blocking the thread.
Normally, for my other functions in the clients listening thread, I'd use invokes to update the UI of the main form, so I guess what I'm asking for is if here's a way to invoke a new form on the main form.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这是 Windows 窗体而不是 WPF?在后台线程中,您不应尝试创建任何表单、控件等或操作它们。这只适用于运行消息循环并可以处理 Windows 消息的主线程。
因此,要让代码在主线程而不是后台线程上执行,您可以使用 Control.BeginInvoke 方法,如下所示:
要记住的主要事情是,如果后台线程不需要主线程的任何响应,线程中,您应该使用 BeginInvoke,而不是 Invoke。否则,如果主线程忙于等待后台线程,则可能会陷入死锁。
I assume this is Windows Forms and not WPF? From your background thread, you should not attempt to create any form, control, etc or manipulate them. This will only work from the main thread which has a message loop running and can process Windows messages.
So to get your code to execute on the main thread instead of the background thread, you can use the Control.BeginInvoke method like so:
The main thing to keep in mind is that if the background thread doesn't need any response from the main thread, you should use BeginInvoke, not Invoke. Otherwise you could get into a deadlock if the main thread is busy waiting on the background thread.
您基本上自己给出了答案 - 只需使用 Invoke 执行代码以在 GUI 线程上创建表单。
You basically gave the answer yourself - just execute the code to create the form on the GUI thread, using Invoke.