D#E の世界

My Life, My Journey, My Thought mostly in Japan

C# Updating ProgressBar inside Thread

Posted by D#E on March 12, 2008

Today my boss told me to learn about threading in C#. And I decided to use my previously finished FileSplitter program that I created. The idea is to add a progress bar so when the File is being processed, the bar would update itself in different thread.

After coding it, I got un-handled runtime exception. Apparently while thread could access the TextBox’s text element, it couldn’t access a GUI event handled element such as progress bar and or combo box. This is where the delegates come in (I heard about delegates last year but never intended to learn it throughly).

Delegates is actually just a function pointer just like in C or C++, in C# they change the system into delegates.

first of all you need to declare the delagate in your class

delegate void UpdateProgressDelegate();

after that make a function


void UpdateProgress()
{
//do some work here to update progress
//for example progressbar1.value = 10;

}

last one is to invoke it inside the thread

this.invoke(new UpdateProgressDelegate(UpdateProgress));

there you go. but you may ask what if I want to add parameters.

While I haven’t tried it myself but this link have the solution for that. Not only that, one of the post on that link stated that it’s better to use component called backgroundworker in order to achieve the same result.

The thread is extremely slow, my FileSplitter program run faster without the updating progress bar. I might gonna try the backgroundworker later on to compare the speed.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>