VB.Net. Multi-Threading with background worker and delegate.

multithreading is the process of creating threads and assigning task to each thread and each thread works simultaneously and thus increasing the efficiencey – wiki.answers.com

Image

Complete Code:

Public Class frmBackGroundWorker
    Private Delegate Sub progressDelegate(ByVal progress As String)

    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        For i As Integer = 0 To 50000
            Dim m_UpdateText As progressDelegate
            m_UpdateText = New progressDelegate(AddressOf progress1)
            Me.Invoke(m_UpdateText, i.ToString)
        Next
    End Sub

    Private Sub BtnStartCounting_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartCounting.Click
        btnSayHello.Enabled = True
        BackgroundWorker1.RunWorkerAsync()

    End Sub

    Private Sub progress1(ByVal progress As String)
        Label1.Text = progress
        ProgressBar1.Minimum = 0
        ProgressBar1.Maximum = 50000
        ProgressBar1.Value = CInt(progress)
    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        MsgBox("Done proccessing")
        btnSayHello.Enabled = False
        lblHelloOutput.Text = ""
    End Sub

    Private Sub btnSayHello_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSayHello.Click
        lblHelloOutput.Text = "Hello" & Environment.UserName & ", I can perform other task while the thread is running."
    End Sub
End Class
This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

Leave a comment