Wednesday, August 17, 2011

How to use backgroundworker control

Hi, Please note, The control Backgroundworker is available with Visual Studio 2008 and Visual Studio 2010.

Backgroundworker:
is used when you need to work with Threads parallely.
For Example

1. if you want to show the file names along with files being copied or
2. file content in label (line by line) with Progressbar etc.

I'm using the 2nd example here for demonstration but you can implement with any similar kind of task.

Steps:


1. Start-->Programs-->Microsoft visual Studio 2010-->Microsoft visual Studio 2010.

2. Create new window application by selecting File-->New-->Project-->Windows Form Application.

3. Goto ToolBox, if not visible Select View-->ToolBox from menubar or Press(Ctrl + Alt + X).


4. Scroll to Component, Select BackgroundWorker and drag to Windows application.


5. Now Drag Button, Label and Progressbar on windows form.


6. Inside button clcik event write this code:


With Me.BackgroundWorker1
.WorkerReportsProgress = True
.RunWorkerAsync("C:\crp.txt")
End With
ProgressBar1.Minimum = 1
ProgressBar1.Maximum = 2000
ProgressBar1.Visible = True
ProgressBar1.Value = 1

7. Note, BackgroundWorker control has three event,


1. BackgroundWorker1_DoWork
2. BackgroundWorker1_ProgressChanged
3. BackgroundWorker1_RunWorkerCompleted


Paste these code in your program:
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim filename As String = e.Argument
Using reader As New System.IO.StreamReader(filename)
While Not reader.EndOfStream
Me.BackgroundWorker1.ReportProgress(0.0, reader.ReadLine())
System.Threading.Thread.Sleep(1000)
End While
End Using

End Sub

Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Me.Label1.Text = e.UserState
ProgressBar1.PerformStep()
End Sub


Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MsgBox("Done reading the file!")

End Sub

8. Run the application, You may see the screen as shown below:



Your comment will be appreciated.