Archive

Posts Tagged ‘winform’

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();
       }
Categories: DEV Tags: , ,