Sunday 3 May 2009

Threading in ASP.NET pages: How to

A very interesting technique that is sometimes not used is the idea of threading and using it in your ASP.NET application. What is really good for is when you have a long running call (such as a function that does a lookup against DNS) and you don’t want to delay the execution of your page.

So how do you do threading in ASP.NET

In this example I will just do a quick run through of creating a threaded operation that could be used for example to save some information to the database, such as a roll your own analytics object.

Firstly you will need to a reference the assembly System.Threading ie
using System.Threading;
I have a small sample class that will contain the IP address, the host name for that IP and the date it was created.
public class TrackingObject 
public string HostIP { get; set; }
public string HostName { get; set; }
public string DateEntered { get; set; }
Next thing is that we need to create a new object on the page load and set some information
TrackingObject trackingObject = new TrackingObject(); 
trackingObject.DateEntered = DateTime.Now.ToString();
trackingObject.HostIP = Request.UserHostAddress;
So we get the IP of the requesting computer and current date and time and set those properties.

Now we are going to create a thread so that we can do a DNS lookup on the IP and then theoretically save this information to the database.

Because we are passing our object into our thread delegate so we need to use the ParameterizedThreadStart Delegate
Thread trackingThread = new Thread(new ParameterizedThreadStart(SaveTrackingInfo));
SaveTrackingInfo is a new function which takes a single object and we will go through that in a minute.

Next thing is to set the priority of the thread we are creating. Thread priority defines which thread gets the resources, the higher the priority of the thread the quicker it will get the resources. On the flip side, if you raise your thread’s priority to a higher level you can cause locks and other problems.

Finally in this section we need to actually start the thread and pass it the object.
Now we will take a look at the SaveTrackingInfo function. This is the function that will be run in the thread.
private void SaveTrackingInfo(object obj)     
TrackingObject trackingObject = (TrackingObject) obj;
trackingObject.HostName = Dns.GetHostEntrytrackingObject.HostIP).HostName;
trackingObject.HostName = trackingObject.HostIP;
} //Save tracking object to the database

We need to cast the object to correct type, because we are passing in a base object.

For this example, we are going to try and get the host name for the IP, which could take some time and then save this object to the database.

This very quick sample shows how to use threading in an ASP.NET application.

You can download the solution from here

In a later post, I will demonstrate what we can do with some of this information.

No comments: