Background Worker

Heres your chance to share your own tutorials with the community. Just post them on here. If your lucky they may even be posted on the main site.
1 post Page 1 of 1
Contributors
User avatar
MrAksel
C# Coder
C# Coder
Posts: 1758
Joined: Fri Mar 26, 2010 12:27 pm

Background Worker
MrAksel
You might have wondered how to use the background worker component? Well just read through this tutorial and you'll know.
The BackgroundWorker is a component that allows you to do operations on a separate thread. (Read about threads: viewtopic.php?f=38&t=4250) There are two properties of the BackgroundWorker; WorkerSupportsCancellation and WorkerReportsProgress. Their names says everything.

When you have created your project and added one BackgroundWorker set the WorkerReportsProgress property to True, add a button that says "Start" and a Label. In this tutorial we will do mathematical operations to show how the Worker works.
Double-click your start button and type in BackgroundWorker1.RunWorkerAsync()

Then double click your BackgroundWorker so you bring up the DoWork event. Here is what all of our work is done. Remember that this is on another thread, so you can the not access controls as you would otherwise. The code is
Code: Select all
        For i As Integer = 1 To 1000
            For j As Integer = 1 To 100000
                Dim k = i * j + Math.Sqrt(i / j) * Math.Pow(i, j / 10000)
            Next
            BackgroundWorker1.ReportProgress(i / 10)
        Next

The work that is done is simply some math functions repeated 100 million times. The parameter passed to the ReportProgress function is the percentage done. You can access it in the ProgressChanged event by using e.ProgressPercentage. It is a value between 0 and 100. Our ProgressChanged event contains the following code:
Code: Select all
Label1.Text = e.ProgressPercentage & "%"
It sets Label1's text to the percentage done.

This is pretty much the basics of a BackgroundWorker.
LMAOSHMSFOAIDMT
Laughing my a** of so hard my sombrero fell off and I dropped my taco lmao;


Over 30 projects with source code!
Please give reputation to helpful members!

Image
Image
1 post Page 1 of 1
Return to “Tutorials”