Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using thread to open form

I am currently studying VB.NET and I got question about using thread to open the form.

For example, when I click open button, then tread will start and open another form to adding or changing data.

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 frmBuild by thread. Do I need to use other method to open form?

And, How can we kill the thread when fromBuild closes?

like image 584
Bob Ma Avatar asked Oct 25 '13 17:10

Bob Ma


1 Answers

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. BackgroundWorker is a common means of handling the work.

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.Run to display the form, and that form must be created on the proper thread:

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 ?

The thread will automatically shut down when the form is closed, if it's written as shown above.

like image 110
Reed Copsey Avatar answered Nov 01 '22 16:11

Reed Copsey