Accessing UI thread controls from 2 joining multi

2020-05-06 08:16发布

I'm currently working on a small auto-update project for my company. After some research on multi-threading, I manage to built up the code below :

Thread #01 :

Private Sub startUpdate()
    If InvokeRequired Then
        Invoke(New FTPDelegate(AddressOf startUpdate))
    Else
        'some code here
    End If
End Sub

Thread #02 which is joined by thread #01 :

Private Sub startProcess()
    myThread = New Thread(Sub() startUpdate())
    myThread.Start()
    myThread.Join()

    'another code goes here

    Me.close
End Sub

And thread #02 is accessed when the form loads :

Private Sub SUpdater_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    myThread1 = New Thread(Sub() startProcess())
    myThread1.Start()
End Sub

There are 2 things which I'm stuck with :

  • I can't access Me.close from thread #01. It fires an error:

    Control is in another thread

  • The main form froze even though I called another thread.

Please help me fix this error.

Thank you very much.

1条回答
何必那么认真
2楼-- · 2020-05-06 09:11

Invocation is required every time you are to access UI elements. Calling Me.Close() starts to dispose all the form's elements (components, buttons, labels, textboxes, etc.), causing interaction with both the form itself, but also everything in it.

The only things you are not required to invoke for are properties that you know doesn't modify anything on the UI when get or set, and also fields (aka variables).

This, for example, would not need to be invoked:

Dim x As Integer = 3

Private Sub Thread1()
    x += 8
End Sub

To fix your problem you just need to invoke the closing of the form. This can be done simply using a delegate.

Delegate Sub CloseDelegate()

Private Sub Thread1()
    If Me.InvokeRequired = True Then 'Always check this property, if invocation is not required there's no meaning doing so.
        Me.Invoke(New CloseDelegate(AddressOf Me.Close))
    Else
        Me.Close() 'If invocation is not required.
    End If
End Sub
查看更多
登录 后发表回答