Backgroundworker example

Posted in .NET 2.0 | Performance | Visual Studio 2005 at Tuesday, 10 February 2009 17:57 GMT Standard Time

The background worker allows you to execute intense or long operations on a separate thread, without having to deal with threads, invokes or delegates. This is essential in today's cluttered webspace brought forth by the constant growth of broadband technology.

This simple example pretty much cover all posibilities of use of this component: cancellation support, backgroundworker error handling and report progress (also passing UserState data on report progress notifications)

Nota: Este artículo está disponible en castellano aquí

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace BackgroundWorker
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //mandatory. Otherwise will throw an exception when calling ReportProgress method
            backgroundWorker1.WorkerReportsProgress = true; 

            //mandatory. Otherwise we would get an InvalidOperationException when trying to cancel the operation
            backgroundWorker1.WorkerSupportsCancellation = true;
        }



        //This method is executed in a separate thread created by the background worker.
        //so don't try to access any UI controls here!! (unless you use a delegate to do it)
        //this attribute will prevent the debugger to stop here if any exception is raised.
        //[System.Diagnostics.DebuggerNonUserCodeAttribute()]
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //NOTE: we shouldn't use a try catch block here (unless you rethrow the exception)
            //the backgroundworker will be able to detect any exception on this code.
            //if any exception is produced, it will be available to you on 
            //the RunWorkerCompletedEventArgs object, method backgroundWorker1_RunWorkerCompleted
            //try
            //{
                DateTime start = DateTime.Now;
                e.Result = "";
                for (int i = 0; i < 100; i++)
                {
                    System.Threading.Thread.Sleep(50); //do some intense task here.
                    backgroundWorker1.ReportProgress(i, DateTime.Now); //notify progress to main thread. We also pass time information in UserState to cover this property in the example.
                    //Error handling: uncomment this code if you want to test how an exception is handled by the background worker.
                    //also uncomment the mentioned attribute above to it doesn't stop in the debugger.
                    //if (i == 34)
                    //    throw new Exception("something wrong here!!");

                    //if cancellation is pending, cancel work.
                    if (backgroundWorker1.CancellationPending)
                    {
                        e.Cancel = true; 
                        return;
                    }
                }

                TimeSpan duration = DateTime.Now - start;
                
                //we could return some useful information here, like calculation output, number of items affected, etc.. to the main thread.
                e.Result = "Duration: " + duration.TotalMilliseconds.ToString() + " ms.";
            //}
            //catch(Exception ex){
            //    MessageBox.Show("Don't use try catch here, let the backgroundworker handle it for you!");
            //}
        }


        
        //This event is raised on the main thread.
        //It is safe to access UI controls here.
        private void backgroundWorker1_ProgressChanged(object sender, 
            ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage; //update progress bar
            
            DateTime time = Convert.ToDateTime(e.UserState); //get additional information about progress
            
            //in this example, we log that optional additional info to textbox
            txtOutput.AppendText(time.ToLongTimeString());
            txtOutput.AppendText(Environment.NewLine);            
        }



        //This is executed after the task is complete whatever the task has completed: a) sucessfully, b) with error c)has been cancelled
        private void backgroundWorker1_RunWorkerCompleted(object sender, 
            RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled) {
                MessageBox.Show("The task has been cancelled");
            }
            else if (e.Error != null)
            {                
                MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());
            }
            else {
                MessageBox.Show("The task has been completed. Results: " + e.Result.ToString());
            }
            
        }




        private void btoCancel_Click(object sender, EventArgs e)
        {
            //notify background worker we want to cancel the operation.
            //this code doesn't actually cancel or kill the thread that is executing the job.
            backgroundWorker1.CancelAsync();
        }

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

      
    }
}

Download sample project

Download BackgroundWorker.ZIP (C# sample project)

AddThis Social Bookmark Button

If you go to Build-> Publish Web Site menu on Visual Studio 2005, you will find this publishing screen:

If you UNCHECK the "Allow this precompiled site to be updatable", all the aspx pages within the projects will be generated empty. To be more exact, you will find the following unique line on them:

This is a marker file generated by the precompilation tool, and should not be deleted!

If you compare this screenshot:

with this one:

you will realize how the first was published allowing ASPX pages to be updated and the second not (notice how in second screenshot, all the ASPX files have 1kb file size)

Don't worry!, All HTML markup and inline code is compiled into assemblies on the bin folder, and it is correctly executed and rendered when the page is requested.

This way, nobody would be able to change either code or HTML content after the publishing is done!

AddThis Social Bookmark Button

I am sure you know how to add the predefined TextBox or ComboBox controls to a Windows Forms context Menu:

Just wanted to quickly show you how you can add your own custom controls to that context menu by using the ToolStripControlHost class, like this (the yellow panel is a user control):

Here is a short video:

And here is the code:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //instance my control
            UserControl1 c = new UserControl1();

            //pass as parameter to ToolStripControlHost instance
            ToolStripControlHost host = new ToolStripControlHost(c);

            //add ToolStripControlHost object to context menu. simple!
            contextMenuStrip1.Items.Add(host);
        }
    }
}


 

AddThis Social Bookmark Button

Using a RAM drive to compile Visual Studio .NET projects

Posted in .NET 2.0 | Performance | Productivity | Visual Studio 2005 | RAM disk at Saturday, 15 December 2007 10:18 GMT Standard Time
(updated 22 dec 07)

After reading some blog posts like this I decide to test on my computers how important is hard disk speed in order to increase your productivity when compiling Visual Studio solutions with more than a few project.

I also wanted to see the gain if I placed my solution (more than 25 projects) in a RAM drive disk instead of the hard disk (be sure you backup frecuently if you do that, or get one of this things to avoid data lost).

In order to create a RAM drive, I download the trial version of Virtual Hard Drive Pro
 from FarStone.

There are the results:

1. Environment hardware information

My desktop:
  1. CPU: AMD Sempron, 1800 MHz
  2. RAM: 2 x (1 Gb Kingston)
  3. Hard disks (2):
    1. System: ATA-100 40 Gb Barracuda 7200 rpm. Average seek: 8.5 ms. Buffer size: 2Mb. Average read speed: 40 Mb/second (*).
    2. Data and code: SATA 200 Gb Barracuda 7200 rpm. Average seek: 8.5 ms. Buffer size: 8 Mb. Average read speed: 50 Mb/second (*).
  4. RAM drive speed (read): 900 Mb/sec
My laptop (Toshiba Satellite Pro M70):
  1. CPU: Intel Pentium Celeron 1.73 Ghz
  2. RAM: 2 x (512 Mb Toshiba)
  3. Hard disk (1) : Toshiba 5400 rpm. Average read speed: 30 Mb/second (*)
  4. RAM drive speed (read): 1500 Mb/sec
* (Hard disk speed tests have been done with HD_Speed from www.steelbytes.com)

2. The Microsoft Visual Studio solution

A Microsoft Visual Studio .NET 2005 solution with 26 projects (Windows Forms and Windows library projects mainly), in C#.

3. Results

Compilation:

Desktop machine:

a) Compilation on hard disk (no RAM Drive installed yet): 72 seconds*
b) Compilation on a 500 MB RAM Drive : 71 seconds*

Laptop machine:

a) Compilation on hard disk (no RAM Drive installed yet): 65 seconds*
b) Compilation on a 400 MB RAM Drive : 32 seconds*

*(average of three compilations)

4. Conclusions:

Seems like my desktop doesn't have much processor power, and the bottleneck is mainly on the CPU, since there is not much different results on readig from a 50 Mb/seconds hard disk or from a 900 MB/second one (the RAM Drive)

My laptop, instead has a slower disk drive but more processor power, so there is a lot of difference between compiling from hard disk and RAM drive. (it took half the time on the RAM disk - also RAM disk read speed is higher than in the desktop)

I still will do more tests with some other combinations of CPU and hard disk..

Feel free to do the above tests yourself and share the results.

Updated:
  • 22 dic 07: Added test with laptop. Desktop tests done again.

AddThis Social Bookmark Button