从线程实例化对象调用委托

时间:2013-03-24 00:07:59

标签: .net vb.net

有没有人知道如何从一个在线程中运行的实例化类调用主Form页面上的函数?

Public Class Test
    Public Sub Temp()
        Try
            'Operations here
        Catch ex as Exception
            Form1.Invoke(New Form1.LogMessageDelegate(AddressOf frmIP.LogMessage), "Error Message To Be Outputted to TextBox on Main Form")
        End Try
    End Sub
End Class

我希望它在函数中返回一个字符串,但是如果有异常,我只调用文本框消息。 谢谢你的时间!

1 个答案:

答案 0 :(得分:0)

Public Class Test
 Public Event ErrorMessage(errStr As String)
 Public Sub Temp()
    Try
        'Operations here
    Catch ex as Exception
        RaisEvent ErrorMessage(ex.Message)
    End Try
 End Sub
End Class

Public Class Form1
  Private Sub form1_load() Handles Me.Load
    Dim trd As New Thread(AddressOf RunTestClass)
    trd.Start()
  Ens Sub

  Private Sub RunTestClass()
    Dim _test As New Test
    Addhandler _test.ErrorMessage, AddressOf Test_ErrorMessage
    _test.Temp()
  End Sub

  Private Sub Test_ErrorMessage(errStr As String)
    Me.Invoke(Sub()
              'run code here for UI thread
              End Sub)
  End Sub
End Class