Every good developer should understand the basics of how Threads and Processes work on the platform they are writing applications for. For us it’s the Windows operating system and using the .Net Framework it’s even easier to harness the power of Multithreading.
Good Multithreading design can vastly improve your applications user experience and I have a little example below of how Multithreading can be used within an ASP.Net 2.0 website.
Our goal here is to send a request to the server and write out 101 lines to a text file on the webserver. The WriteOutTextFile() method takes a very long time to complete as I have deliberatly made the method run slow by making the thread go to sleep for 500ms every iteration of the loop. Now say this method was used as a logging tool behind the scenes, we wouldn’t want our user waiting for the method to write out all 101 lines before the web page was returnd to them. The user doesn’t care that your logging method takes a long time they just want to see their request returned to them, this is where multithreading comes in. We open up a new web site in Visual Studio and we have a simple application as shown below:
I put one label and one button on the form and our markup looks like this:
We then switch to our code behind and write the following code in the OnLoad event:
Here the first thing we are doing is setting the label’s text property to “PostBack!” which is pretty standard stuff, the interesting part is the next four lines. In version 2.0 of the .Net Framework multithreading was made so much easier by introducing the ThreadStart class which allows us to easily pass the method we want to be called when our threads starts to the Thread class. The ParameterizedThreadStart class makes things even easier when you want to pass arguments to your methods and anyone who has done multithreading in .Net 1.1 knows how much of a headache this was. So what we are doing in these four lines is creating an instance of the ThreadStart class to tell our new thread to call our worker method WriteOutTextFile when we start out new thread. We then go ahead and create our new Thread and call it’s Start() method. This will kick off our WriteOutTextFile() method on a new thread and allow the OnLoad event to finish execution and return our request back to the user. Our new thread will continue executing and writing to our text file in the background. The WriteOutTextFile() method looks like this:
That’s a simple example of how multithreading can be used to good effect with the .Net 2.0 framework. As you can see it’s a very powerful tool and mastering multithreading can make your applications more performant, much more scalable and give your end user and less frustrating experience. I have uploaded the source code here, if you want to download and anaylse it yourself.