A while back I was doing some work on my latest personal
project at home (more on that later), and encountered a situation where
I needed to run a long-running, resource intensive method, while at the
same time updating a label control on a windows form. The process
wasn't working very well, as the label wasn't getting updated properly,
or in a timely manner, because the other method was using up all of the
processor time allocated to the thread that they were both running in.
So, I needed to figure out how to spin up the long-running method on a
separate thread. I've never done any sort of multi-threading before,
and didn't even really know where to start, so I just started browsing
through all of the classes in the System.Threading namespace to see what my options were.
So, I started out with the Thread
class. That actually seemed to do a pretty good job, and really did
what I needed with one exception. It ran the task on a separate thread,
and the main class was able to update the label control on the form
effectively now, but I had a couple of things that I needed to do once
the threaded task was complete. Unfortunately, the Thread class doesn't
have any sort of mechanism for letting the class that started it know
when it's done doing its thing. So, I needed to figure out how to do my
Thread complete processing. As I was looking through some sample code
in the MSDN library on using the Thread class, I noticed mention of the BackgroundWorker class.
I looked up the documentation for this class, and as it turned out,
that was exactly what I was looking for. From what I can tell (the
documentation doesn't explicitly state this), it handles the process of
spinning up a task on a new thread for you, and it also provides a
number of events that you can subscribe to and handle, including the
very one that I was looking for, RunWorkerCompleted, which fires once the threaded task has completed its processing. Perfect.
if you're working on an application in which you have need to do some
asynchronous, threaded processing, take a look at the BackgroundWorker
class. It might turn out to be just what you need.
09-26-2006 1:14 PM