Sunday, May 31, 2009

C# Background Worker net 2.0

Recently I got code from a programmer who had imported a load of webpages and parsed them. It took quite a long time to do and hence he made the program run in the background without a GUI. This was fine as is was out of the way however I wanted to visually see what was going on if need be. Intitially he had written a log file which was just as fine solution but I wanted to see if I could see it on the screen.

In .net 1.0 we all used Application.DOEvents() however this had a host of problems which I won't go into it here. In .net 2.0 they introduced a Background worker component to do the trick. Basically this component starts up a managed thread that does all the work in background without impacting on the rest of the application.

There was a whole range of samples on this however I found the following link the easiest to do:

http://dotnetdud.blogspot.com/search/label/.NET%20BackGround%20Worker%20Example

Firstly if your starting out using Background worker just drag a component on to the desktop, this is the easiest thing to do. The component has 3 events all critical to using it properly.


DoWork, ProgressChanged,RunWorkCompleted.

DoWork fuuction kicks everything off, when you double click the property a new function will be generated on your screen as below.

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Put your entry point for your code here //
}

In this function should be the entry code of where your program and task starts. So for example if you where writing code for the entry point in the usual button1_Click event then you would want to simply copy and past the main functionality into the backgroundWorker1_DoWork() function.


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

RunWorkerAsync() kick's off the thread and starts the backgroundWorker1_DoWork() which should now have the code you need.

You can also run private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) to keep track of your changes but I just have delegates in my thread code which updates the main form for any changes. Since GUI is free up to listen to changes it will detect these straight away.