Accessing UI thread controls from 2 joining multi thread

前端 未结 1 1938
Happy的楠姐
Happy的楠姐 2021-01-29 05:18

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 :

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-29 05:39

    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
    

    0 讨论(0)
提交回复
热议问题