Home > DEV > Hello World with BackgroundWorker

Hello World with BackgroundWorker

in .Net 2.0 MS introduced the BackgroundWorker component to simplify the life of WinForm developers… you can check the following article to know more information http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

the simples sample of use of the BackgroundWorker is a WinForm application that count from 1 to 999 billion and every time that add 1 million, update a simple textBox on the form…

As you can see code is extremely simple… just remember to enable the WorkerReportProgress to true and use the UserState to pass values between events…

ps. this sample does not support user cancellation and does not handle more than 1 click…

public Form1()
       {
           InitializeComponent();
           backgroundWorker1.WorkerReportsProgress = true;
       }

       private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
       {
           var bckwork = (BackgroundWorker)sender;
           for (Int64 i = 1; i <= 9999999999; i++)
           {
               if ((i % 1000000) == 0)
               {
                   int  prog =  (int)(i / 1000000) ;               
                   bckwork.ReportProgress( prog, i);
               }
           }
       }

       private void button1_Click(object sender, EventArgs e)
       {
           backgroundWorker1.RunWorkerAsync();
       }

       private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
       {
           textBox1.Text = e.UserState.ToString();
       }
Advertisements
Categories: DEV Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: