Carrying on with our primers on Multi-Threading in the .NET framework, we reach the wonderful world of the background thread.
Actions that are performed on the background threads are exactly the same as can be performed on the foreground threads – with 2 differences.
- Foreground threads will have a higher precedence over a background thread with regards to processing time
- When the last foreground thread of a process is stopped, then all the [remaining] background threads launched by the process will stop as well.
I've seen MANY .NET developers make the mistake of using foreground/background thread interchangeably, along with the usage of process and thread. This is what my mother used to tell me is a "BIIIG no no!".
Quick Definition:
A process is a complete application which might run on one (Single Thread) or many (Multi Thread) threads depending on the application design and requirements. In most multithreading operating systems, a process gets its own memory address space; a thread doesn't. Threads typically share the heap belonging to their parent process.
Essentially, creating a background thread is for 2 main reasons.
- You want to run a long running process that would normally lockup the main process which is usually the UI
- You want the process to follow suit with the state of the originating process, so that if you end the application, the background process is killed.
Let's look at the following example application. It's a Windows app that touches ALL the files on a selected drive including all sub folders. This is very time consuming. On my D: drive, the process took over ten minutes and still wasn't complete. Running this as a single thread would lock up the front end and make it unresponsive, rendering the program completely useless until the touching of all the files is complete. You can get a look at this single threaded version of the application here.
As you can see, the front end simply freezes. Running the IO process on a different background thread will unfreeze the frontend as so here. In fact, to prove the point, I've added another button titled Action which when you click will simply pop up a MessageBox and state the time to the second whence it was clicked.
You will notice that Background threads share almost everything (less what was mentioned before) with normal threads. The key difference is by setting the Thread instance's property IsBackGround to True.
Another thing that you should note (something that I'll be blogging about soon) is the need to run the ListBox's Invoke method. This is to make sure that cross thread calls are safe (since we have an originator thread and a background thread, we're now multi-threaded!)
The next time, I'll be talking about the ThreadPool and just how great and simple multi-threading becomes using it.
Mustafa Ismail

2 comments:
It was really usefull to read, but pleas resubmit the second example.
Sorry about that! There you go, the link has been fixed. :)
Post a Comment