vb.net 使用线程打开表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19596091/
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
Using thread to open form
提问by Bob Ma
I am currently studying VB.NET and I got question about using thread to open the form.
我目前正在学习 VB.NET,我遇到了有关使用线程打开表单的问题。
For example, when I click open button, then tread will start and open another form to adding or changing data.
例如,当我单击打开按钮时,tread 将启动并打开另一个表单来添加或更改数据。
Therefore, I tried to implement this part such as
因此,我尝试实现这部分,例如
Private Sub menu_Click(sender As Object, e As EventArgs) Handles menu.Click
Dim A As System.Threading.Thread = New Threading.Thread(AddressOf Task_A)
A.Start()
End Sub
Public Sub Task_A()
frmBuild.Show()
End Sub
However, I am getting error to open the frmBuildby thread. Do I need to use other method to open form?
但是,我在打开frmBuildby 线程时出错。我需要使用其他方法打开表单吗?
And, How can we kill the thread when fromBuild closes?
而且,当 fromBuild 关闭时,我们如何杀死线程?
回答by Reed Copsey
This is almost always a bad idea. You shouldn't try to use a separate thread to open a Form- instead, open all of your forms on the main UI thread, and move the "work" that would otherwise block onto background threads. BackgroundWorkeris a common means of handling the work.
这几乎总是一个坏主意。您不应该尝试使用单独的线程来打开一个Form- 相反,在主 UI 线程上打开所有表单,并将否则会阻塞到后台线程的“工作”移动。 BackgroundWorker是处理工作的常用手段。
That being said, if you need to do this for some unusual reason, you need to do two other things.
话虽如此,如果您出于某种不寻常的原因需要这样做,您还需要做另外两件事。
First, you need to set the apartment state of that thread. You also need to use Application.Runto display the form, and that form must be created on the proper thread:
首先,您需要设置该线程的单元状态。您还需要使用Application.Run来显示表单,并且必须在正确的线程上创建该表单:
Private Sub menu_Click(sender As Object, e As EventArgs) Handles menu.Click
Dim th As System.Threading.Thread = New Threading.Thread(AddressOf Task_A)
th.SetApartmentState(ApartmentState.STA);
th.Start()
End Sub
Public Sub Task_A()
frmBuild = New YourForm() ' Must be created on this thread!
Application.Run(frmBuild)
End Sub
In order to close the Form from the other thread, you can use:
为了从另一个线程关闭表单,您可以使用:
frmBuild.BeginInvoke(New Action(Sub() frmBuild.Close()))
And, How can we kill the thread when fromBuild closes ?
而且,当 fromBuild 关闭时,我们如何杀死线程?
The thread will automatically shut down when the form is closed, if it's written as shown above.
当表单关闭时,线程会自动关闭,如果它是如上所示写的。

