在不使用委托的情况下更新UI(线程)

时间:2018-09-24 18:05:33

标签: vb.net

我知道,当您想从线程内部显示值时,需要使用委托并调用其他函数,否则将抛出非法的跨线程异常。在以下示例中,我不使用委托。是不好还是不好?我应该避免使用它,而只是使用委托来更新UI吗?

Public Class Form1

    Public Class Test
        Public Property i As Integer = 0
        Public Event ReturnValue(v As Integer)
        Public Sub Start()
            Dim T As Threading.Thread = New Threading.Thread(Sub()
                                                                 While True
                                                                     Threading.Thread.Sleep(100)
                                                                     i += 1
                                                                     RaiseEvent ReturnValue(i)
                                                                 End While
                                                             End Sub)
            T.Start()
        End Sub
    End Class

    Public WithEvents TestInstance As New Test

    Private Sub UpdateUI(ByVal v As Integer) Handles TestInstance.ReturnValue
        Invoke(Sub()
                   Label1.Text = v.ToString
               End Sub)
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        TestInstance.Start()
    End Sub

End Class

0 个答案:

没有答案