Site Search:
Sign in | Join | Help

This Blog

4Penny offers domain names

Syndication

Tags

No tags have been created or used yet.

Archives

4Penny.net

Corey McClelland

Personal note from Ace Developer - Corey McClelland

May 2007 - Posts

  • VB.NET Delegates

    Here is a very simple example of delegates in vb.net.  The DelegateExample class is the entry point in the application. 

    The true power of delegates are seen when they are implemented using multiple threads.  That's typically a ui thread and multiple worker threads that update the ui.

    Public Class DelegateExample
        Shared Sub main()
            Dim s As New Status()
            s.beginWorker()
        End Sub
    End Class

    Imports System.Windows.Forms

    Public Class Status

        Sub New()

        End Sub

        Public Sub beginWorker()
            Dim w As New Worker()
            w.NotifyOnWorkerEventHapened(New Worker.workerEventHappened(AddressOf localMethod))
            w.beginWork()
        End Sub

        'this function has the same signiture as the delegate
        Public Sub localMethod(ByVal strMsg As String)
            MessageBox.Show(strMsg)
        End Sub

    End Class

     

    Public Class Worker

        Public Delegate Sub workerEventHappened(ByVal strMsg As String)
        Private weh As workerEventHappened

        Public Sub NotifyOnWorkerEventHapened(ByVal value As workerEventHappened)
            weh = value
        End Sub


        Sub New()

        End Sub

        Public Sub beginWork()
            weh.Invoke("Event Happened!")
        End Sub

    End Class