Asynchronous Programming Technique
for Advanced Programmers

Dear Folks,

I suppose the following programmer would be helpful to you all........

 

Dim i As Integer

 

Private Sub GO_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GO.Click

        If Not TextBox1.Text = "" Then

            Dim i As Integer = CInt(TextBox1.Text)

            BackgroundWorker1.RunWorkerAsync(i)

        End If

End Sub

 

Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click

        BackgroundWorker1.CancelAsync()

End Sub

 

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

 

        i = CInt(e.Argument)

        For j As Integer = 0 To i

            If (BackgroundWorker1.CancellationPending = True) Then

                e.Cancel = True

                Exit For

            End If

            System.Threading.Thread.Sleep(1000)

            BackgroundWorker1.ReportProgress(CInt(j * 100 / i))

        Next

End Sub

 

Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged

        ProgressBar1.Value = e.ProgressPercentage

End Sub

 

 

RunWorkerAsync Method

 

This is the one method of Backgroundworker Component.

Its used to execute the Background process by raising the DoWork event.

The code in the DoWork event handler is execute on seperate thread.

We wirte our time consuming process in that event.

 

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

 

       'Write the time consuming process.

End Sub

 

ds

 

Any where in your code,starts the time consuming process on seperate thread by calling the RunWorkerAsync method.

 

Ex:I Wrote that in my button clicl event.

 

Private Sub GO_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GO.Click

        If Not TextBox1.Text = "" Then

            Dim i As Integer = CInt(TextBox1.Text)

            BackgroundWorker1.RunWorkerAsync(i) 'Parameter is optional if its file                                                                    '(BackgroundWorker1.RunWorkerAsync(file path)

        End If

End Sub

 

RunWorkerComplted Method

 

When background process is terminated whether because that process is completed or cancelled,the RunWorkerCompleted event is raised.

This event is used to alert the users when the background process is completed or not.

 

Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted

        If (e.Cancelled) Then

            MsgBox("Process was cancelled")

        Else

            MsgBox("Process was completed" & e.Result.ToString)

        End If

End Sub

 

Cancelling the Background process

 

1>Set the WorksSupportsCancellation property of BackgroundWorkerComponent as True

2>Create the method that cancell the background operation.

 Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

        BackgroundWorker1.CancelAsync()

End Sub

3>In the Background worker DoWork event handler polling the BackgroundWorkerCancelling property,and implement code to cancel the operation if its True.

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

        If BackgroundWorker1.CancellationPending Then

            e.Cancel = True

        End If

End Sub

 

Reporting the Background process with BackgroundWorker.

 

1>Set the WorkerReportsPrgress property of BackgroundWorkerComponent as True

2>

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

        i = CInt(e.Argument)

        For j As Integer = 0 To i

            BackgroundWorker1.ReportProgress(CInt(j * 100 / i))

        Next

End Sub

3>

Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged

        ProgressBar1.Value = e.ProgressPercentage

End Sub

 

Requesting the status of the background process

1>IsBusy property returns the boolean value which indicate the process of background working.

If Not BackgroundWorker1.IsBusy

BackGroundWorker1.RunWorkerAsync()

End IF

 

 

Implementing Asynchronous Methods.

 

Using the Delegates:

Special classes called Delegates allow you to call a method in a variety of different ways.

A delegate is essentially type-safe function pointer.

It allow you to pass a reference to an entry point for a method and invoke method in a variety of ways without making an explict function call.

Delegate keyword is used to declare the Delegate.

You must specify the same method signature as that method that you want to call with the delegate.

 

1>One method name as add

 Public Function add(ByVal a As String, ByVal age As Integer) As String

        ans = a & age

        Return ans

 End Function

2>Declare the delegate name as mydelegate

Public Delegate Function mydelegate(ByVal b As String, ByVal tt As Integer) As String

3>Create the instance for the delegate

Dim obj1 As New mydelegate(AddressOf add)

4>Invoke the Object

Label1.Text = obj1(a, age)

 

Using the Delegates Asynchronously:

 

Normally 2 methods in  Delegates are used to call the delegate Asynchronously.

1>BeginInvoke

It is used to start the delegate in seperate thread.

2>EndInvoke

Calling EndInvoke method retrieves the result of that method and ends the SeperateThread.

BeginInvoke returns an instance of IAsyncResult which is used to monitor the Asynchronuous call.

You can use BeginInvoke and EndInvoke in several ways to implement asynchronous methods.

 

A>Waiting for Asynchronous call to Return with EndInvoke

ex:

Dim d1 as New mydelegate(Address of method)

Dim result as IAsyResult

result=d1.BeginInvoke(342,nothing,nothing)//{nothing parameters are DelegateCallback,AsyncState}

dim result as string

result=d1.EndInvoke(result)

 

The potential Disadvantage of this method:EndInvoke call is block the execution of the thread until the asynchronous operation is completed if it has not complete yet.

 

B>Polling IAsyncResult Until Completion

 

1>Call the BeginInvoke

2>Poll the IsCompleted property of IAsyncResult to determine if the Operation has finished.

3>Then you can call the EndInvoke method.

ex:

Dim d1 as New mydelegate(Address of method)

Dim result as IAsyResult

result=d1.BeginInvoke(342,nothing,nothing)//{nothing parameters are DelegateCallback,AsyncState}

while Not Result.IsCompleted

' do some work

End While

dim resultString as string

resultString=d1.EndInvoke(result)

 

The potential Adadvantage of this method:you need not want to call the EndInvoke call untill the process has been completed.