dotnet thoughts 

a dotnet developer's technical blog

Working with backgroundworker class

From .Net 2.0 Framework Microsoft added a new class, which helps us to implement background processing, without touching the Threads. :) According to MSDN, Background Worker- Executes an operation on a separate thread. It is very easy to use background worker to implement background thread scenarios.

Sample Implementation – This is a sample application, which updates the UI based on the password strength.


Private WithEvents m_Worker As System.ComponentModel.BackgroundWorker
Sub New()
InitializeComponent()
m_Worker = New System.ComponentModel.BackgroundWorker
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
m_Worker.RunWorkerAsync("Password")'Pass the argument over here.
End Sub
'You need to add the code block, which you require to Run Asynchronous or run in background.
Private Sub m_Worker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles m_Worker.DoWork
Dim password As String = e.Argument
Dim strength As Integer = 0
'Password Strength calculation algorithm
e.Result = strength
End Sub
'The code to Update the UI will be over here
Private Sub m_Worker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles m_Worker.RunWorkerCompleted
'Update UI
Dim result As Integer = e.Result
End Sub

You can get more information about background worker in MSDN. And this article gives a good example of background worker.

No related content found.

No Responses to “Working with backgroundworker class”

RSS feed for comments on this post. TrackBack URL

Leave a Response

*