【问题标题】:Raising an event on a new thread in VB.NET在 VB.NET 的新线程上引发事件
【发布时间】:2012-02-13 04:10:49
【问题描述】:

我需要在新线程上的表单中引发事件。

(我不认为这样做的原因是相关的,但以防万一:我将从表单的 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 中的事件实际上是由后台的委托组成的。有没有办法在新线程中引发事件而不为每个线程创建子?或者,我应该使用更合适的方法吗?

【问题讨论】:

  • 为什么需要在新线程上引发事件?
  • @Matt,阅读我的帖子,第一段斜体。我需要在 WndProc 中引发事件。如果处理这些事件的代码需要 WndProc 消息才能工作,则会发生崩溃,因为 WndProc 被阻塞。

标签: vb.net multithreading events delegates


【解决方案1】:

您可以像这样消除 RaiseMyEvent 子:

Public Class Class1

    Public Event MyEvent()

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

End Class

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      • 2015-04-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 2011-04-07
      相关资源
      最近更新 更多