vb.net 如何在单独的线程上运行 VB 项目中的表单,同时仍然能够进行通信

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17481930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:09:47  来源:igfitidea点击:

How to run forms in VB project on separate threads while still being able to communicate

vb.netmultithreading

提问by TheRyan722

I have been stuck with this issue for quite a long time. I have a VB.Net project, where I have several forms. However, if one of the forms freezes or crashes, the whole application crashes. I have not been able to find a way to be able to, when each form is displayed it is either in a separate process, or new thread and be able to retain the ability to communicate with other forms, as if it was on the main UI thread. I am in desperate need of finding a way to do this, but every time I create a new thread with a new form, the form immediately closes. Is this even possible?

我已经被这个问题困扰了很长时间。我有一个 VB.Net 项目,其中有几种形式。但是,如果其中一个表单冻结或崩溃,整个应用程序就会崩溃。我一直无法找到一种方法,当每个表单显示时,它要么在单独的进程中,要么在新线程中,并且能够保留与其他表单通信的能力,就好像它在主线程上一样界面线程。我迫切需要找到一种方法来做到这一点,但是每次我用新表单创建一个新线程时,该表单都会立即关闭。这甚至可能吗?

回答by Andreas

There are two things you should know.

有两件事你应该知道。

While it is perfectly possible to have two separate forms run on two separate threads, it is a bad design (unless you really know what you're doing). If you want to create a form on a separate thread, then you are also responsible for creating a message loop on that thread (otherwise your form will freeze).

虽然在两个单独的线程上运行两个单独的表单是完全可能的,但这是一个糟糕的设计(除非你真的知道你在做什么)。如果您想在单独的线程上创建表单,那么您还负责在该线程上创建消息循环(否则您的表单将冻结)。

Concretely, you do this with Application.Run

具体来说,你这样做 Application.Run

    _thread = New Thread(Sub()
                             Using frm As New SomeForm
                                 Application.Run(frm)
                             End Using
                         End Sub)
    _thread.Start()

Communication between forms on different threads is no different from communication between a normal thread and a form. You could use a ConcurrentQueueof messages into which one thread writes instructions for the other thread to read, or simple shared variables. You have to make sure that each thread only changes components or controls of the form it created. To manipulate controls between threads, you have to use Invoke.

不同线程上的表单之间的通信与普通线程和表单之间的通信没有区别。您可以使用一ConcurrentQueue组消息,其中一个线程将指令写入另一个线程以读取,或者使用简单的共享变量。您必须确保每个线程只更改它创建的表单的组件或控件。要在线程之间操作控件,您必须使用Invoke.