在VB.NET中的新线程上引发事件

时间:2012-02-13 04:10:50

标签: vb.net multithreading events delegates

我需要在新主题上从表单中引发事件。

(我不相信这个的原因是相关的,但以防万一:我将从表单的WndProc子中的代码中引发事件。如果处理事件的代码阻塞了表单上的内容[例如msgbox],然后在断开连接的上下文中发生了各种各样的麻烦。我已经确认在修复问题的新线程上引发事件。)

这就是我目前正在做的事情:

Public Event MyEvent()

Public Sub RaiseMyEvent()
    RaiseEvent MyEvent
End Sub

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    Dim t As New Threading.Thread(AddressOf RaiseMyEvent)
    t.Start()
End Sub

有更好的方法吗?

据我所知,VB中的事件实际上是由后台的代表组成的。有没有办法在新线程中引发事件而不为每个线程创建子线程?或者,我应该使用更合适的方法吗?

2 个答案:

答案 0 :(得分:4)

不知道这是否会有所帮助,但我总是会做这样的线程和事件:

Event MyEvent(ByVal Var1 As String, ByVal Var2 As String)

Private Delegate Sub del_MyEvent(ByVal Var1 As String, ByVal Var2 As String)

Private Sub StartNewThread()
    'MAIN UI THREAD

    Dim sVar1 As String = "Test"
    Dim sVar2 As String = "Second Var"

    Dim oThread As New Threading.Thread(New Threading.ParameterizedThreadStart(AddressOf StartNewThread_Threaded))
    With oThread
        .IsBackground = True
        .Priority = Threading.ThreadPriority.BelowNormal
        .Name = "StartNewThread_Threaded"

        .Start(New Object() {sVar1, sVar2})
    End With
End Sub
Private Sub StartNewThread_Threaded(ByVal o As Object)
    'CHILD THREAD
    Dim sVar1 As String = o(0)
    Dim sVar2 As String = o(1)

    'Do threaded operation
    Threading.Thread.Sleep(1000)

    'Raise event
    RaiseEvent_MyEvent(sVar1, sVar2)

End Sub

Public Sub RaiseEvent_MyEvent(ByVal Var1 As String, ByVal Var2 As String)

    If Me.InvokeRequired Then
        'Makes the sub threadsafe (I.e. the event will only be raised in the UI Thread)
        Dim oDel As New del_MyEvent(AddressOf RaiseEvent_MyEvent)
        Me.Invoke(oDel, Var1, Var2)
        Exit Sub
    End If

    'MAIN UI THREAD
    RaiseEvent MyEvent(Var1, Var2)
End Sub

答案 1 :(得分:4)

您可以像这样删除RaiseMyEvent子:

Public Class Class1

    Public Event MyEvent()

    Sub Demo()
        Dim t As New Threading.Thread(Sub() RaiseEvent MyEvent())
        t.Start()
    End Sub

End Class