Thursday, March 31, 2011

Raise Events Cross-Thread

    'Author: Aeonhack

    'Notes:
    'Imports System.ComponentModel
    '
    'Raise events in cross-thread operations, no more of those pesky: Cross-thread operation
    'not valid: Control 'NAME' accessed from a thread other than the thread it was created on."
    '
    'I have put together a simple class that reverses a string on a seperate thread and raises an event.
    '
    'It should be noted that Visual Basic hides the delegates for events, you can call them using
    'Name + Event. For example, if we have an event named Disconnect you would pass the following
    'into the Raise method: DisconnectEvent


    'Sample Usage:

    'Class MultiThread
    '    Event Complete(ByVal sender As Object, ByVal text As String)
    '    Sub Something(ByVal text As String)
    '        Dim T As New Threading.Thread(AddressOf DoSomething) : T.Start(text)
    '    End Sub
    '    Private Sub DoSomething(ByVal text As String)
    '        'This will cause a cross thread error.
    '        'RaiseEvent Complete(Me, StrReverse(text))

    '        'This will not.
    '        Raise(CompleteEvent, New Object() {Me, StrReverse(text)})
    '    End Sub
    'End Class

    'Dim WithEvents T As New MultiThread
    'Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    '    T.Something("reverse this string")
    'End Sub
    'Private Sub T_Complete(ByVal sender As Object, ByVal text As String) Handles T.Complete
    '    Me.Text = text
    'End Sub

    'Here is the magic code that will handle all of it for you.
    Shared Sub Raise(ByVal [event] As [Delegate], ByVal data As Object())
        If [event] IsNot Nothing Then
            For Each C In [event].GetInvocationList
                Dim T = CType(C.Target, ISynchronizeInvoke)
                If T IsNot Nothing AndAlso T.InvokeRequired Then T.BeginInvoke(C, data) Else C.DynamicInvoke(data)
            Next
        End If
    End Sub

No comments:

Post a Comment