Click here to Skip to main content
15,896,201 members
Articles / Programming Languages / C#

Asynchronous method calling using events and delegates

Rate me:
Please Sign up or sign in to vote.
4.58/5 (8 votes)
15 Mar 2013CPOL3 min read 41.9K   1.4K   42  
This article describes how to call methods asynchronously using delegates and custom events.
Delegate Sub StatusEventHandler(sender As Object, e As StatusEventArgs)
Delegate Sub ProgressValueChangedEventHandler(sender As Object, e As ProgressValueChangeEventArgs)
Delegate Sub CompletedEventHandler(sender As Object, e As EventArgs)

Public Class Form1

    Sub UpdateLabelStatus(lbl As Label, message As String)
        If lbl.InvokeRequired Then
            lbl.BeginInvoke(New Action(Of Label, String)(AddressOf UpdateLabelStatus), lbl, message)
        Else
            lbl.Text = message
            lbl.Update()
            lbl.Parent.Update()
        End If
    End Sub

    Sub UpdateProgressbar(pbar As ProgressBar, maxVal As Integer, val As Integer)
        If pbar.InvokeRequired Then
            pbar.BeginInvoke(New Action(Of ProgressBar, Integer, Integer)(AddressOf UpdateProgressbar), pbar, maxVal, val)
        Else
            pbar.Maximum = maxVal
            pbar.Minimum = 0
            pbar.Value = val
            pbar.Update()
            pbar.Parent.Update()

            Dim pervalue = String.Format("{0} file(s) processed out of {1}", val, maxVal)
            UpdateLabelStatus(lblProgress, pervalue.ToString())
        End If
    End Sub

    Sub Form1_StatusEvent(sender As Object, e As StatusEventArgs)
        UpdateLabelStatus(lblStatus, String.Format("File {0} {1} successfully", e.Name, e.Status))
    End Sub

    Sub Form1_ProgressValueChanged(sender As Object, e As ProgressValueChangeEventArgs)
        UpdateProgressbar(pBar, e.MaxValue, e.Value)
    End Sub

    Sub Form1_Completed(sender As Object, e As EventArgs)
        UpdateLabelStatus(lblStatus, "NA")
        UpdateLabelStatus(lblProgress, "NA")
    End Sub

    Private Sub btnStart_Click(sender As System.Object, e As System.EventArgs) Handles btnStart.Click
        Dim ed = New TaskToPerform()
        AddHandler ed.StatusEvent, AddressOf Form1_StatusEvent
        AddHandler ed.ProgressValueChanged, AddressOf Form1_ProgressValueChanged
        AddHandler ed.Completed, AddressOf Form1_Completed

        Dim start As New Threading.ParameterizedThreadStart(AddressOf ed.IterateFile)
        Dim t As New Threading.Thread(start)
        t.Start("C:\Windows")
    End Sub
End Class

Public Class StatusEventArgs
    Public Property Name As String
    Public Property Status As String
End Class

Public Class ProgressValueChangeEventArgs
    Public Property MinValue As Integer
    Public Property MaxValue As Integer
    Public Property Value As Integer
End Class

Class TaskToPerform

    Public Custom Event StatusEvent As StatusEventHandler
        AddHandler(value As StatusEventHandler)
            _statusEvent = value
        End AddHandler

        RemoveHandler(value As StatusEventHandler)
            _statusEvent = Nothing
        End RemoveHandler

        RaiseEvent(sender As Object, e As StatusEventArgs)
            If _statusEvent IsNot Nothing Then
                _statusEvent(sender, e)
            End If
        End RaiseEvent
    End Event
    Private _statusEvent As StatusEventHandler

    Public Custom Event ProgressValueChanged As ProgressValueChangedEventHandler
        AddHandler(value As ProgressValueChangedEventHandler)
            _progressValueChange = value
        End AddHandler

        RemoveHandler(value As ProgressValueChangedEventHandler)
            _progressValueChange = Nothing
        End RemoveHandler

        RaiseEvent(sender As Object, e As ProgressValueChangeEventArgs)
            If _progressValueChange IsNot Nothing Then
                _progressValueChange(sender, e)
            End If
        End RaiseEvent
    End Event
    Private _progressValueChange As ProgressValueChangedEventHandler

    Public Custom Event Completed As CompletedEventHandler
        AddHandler(value As CompletedEventHandler)
            _completed = value
        End AddHandler

        RemoveHandler(value As CompletedEventHandler)
            _completed = Nothing
        End RemoveHandler

        RaiseEvent(sender As Object, e As System.EventArgs)
            If _completed IsNot Nothing Then
                _completed(sender, e)
            End If
        End RaiseEvent
    End Event
    Private _completed As CompletedEventHandler

    Public Sub IterateFile(path As String)
        Dim files As String() = IO.Directory.GetFiles(path, "*.*")
        Dim tot As Integer = files.Length
        Dim cnt As Integer = 1

        Dim enumerator = files.GetEnumerator()

        While enumerator.MoveNext()
            Dim fp = New FileProcessing(enumerator.Current)
            AddHandler fp.StatusEvent, AddressOf TaskToPerform_StatusEvent
            fp.Processing()

            If _progressValueChange IsNot Nothing Then
                _progressValueChange(Me, New ProgressValueChangeEventArgs With {.MaxValue = tot, .MinValue = 0, .Value = cnt})
            End If
            cnt = cnt + 1
        End While
        If _completed IsNot Nothing Then
            _completed(Me, New EventArgs())
        End If
    End Sub

    Sub TaskToPerform_StatusEvent(sender As Object, e As StatusEventArgs)
        If _statusEvent IsNot Nothing Then
            _statusEvent(sender, e)
        End If
    End Sub
End Class

Class FileProcessing
    Implements IDisposable

    Public Custom Event StatusEvent As StatusEventHandler
        AddHandler(value As StatusEventHandler)
            _statusEvent = value
        End AddHandler

        RemoveHandler(value As StatusEventHandler)
            _statusEvent = Nothing
        End RemoveHandler

        RaiseEvent(sender As Object, e As StatusEventArgs)
            If _statusEvent IsNot Nothing Then
                _statusEvent(sender, e)
            End If
        End RaiseEvent
    End Event
    Private _statusEvent As StatusEventHandler

    Private ReadOnly filename As String

    Public Sub New(fileName As String)
        Me.filename = fileName
    End Sub

    Public Sub Processing()
        Threading.Thread.Sleep(500)

        If Not IsNothing(_statusEvent) Then
            Dim args = New StatusEventArgs With {.Name = filename, .Status = "Opened"}
            _statusEvent(Me, args)
            Threading.Thread.Sleep(500)
            args.Status = "Processed"
            _statusEvent(Me, args)
            Threading.Thread.Sleep(1000)
            args.Status = "Closed"
            _statusEvent(Me, args)
            Threading.Thread.Sleep(500)
        End If
    End Sub

    Public Sub Dispose() Implements System.IDisposable.Dispose
        GC.SuppressFinalize(Me)
    End Sub
End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader Automation Anywhere Inc.
India India
I am Himanshu Manjarawala, Garduate in Computer Science and MCA From Veer Narmad South Gujarat University, Surat Gijarat India. Currently working as Sr. Software Developer in Automation Anywhere Softwares Pvt. Ltd. Vadodara, Gujarat

Comments and Discussions