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 ieusing System.Threading;
public class TrackingObject
{
public string HostIP { get; set; }
public string HostName { get; set; }
public string DateEntered { get; set; }
}
TrackingObject trackingObject = new TrackingObject();
trackingObject.DateEntered = DateTime.Now.ToString();
trackingObject.HostIP = Request.UserHostAddress;
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));
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.
trackingThread.Start(trackingObject);
private void SaveTrackingInfo(object obj)
{
TrackingObject trackingObject = (TrackingObject) obj;
try
{
trackingObject.HostName = Dns.GetHostEntrytrackingObject.HostIP).HostName;
}
catch
{
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:
Post a Comment