Welcome to Professional ASP.NET - Chris Love's Official Blog Sign in | Join | Help

Chris Love's Official ASP.NET Blog

Chris Love's Helpful tips, tricks and pragmatic development knowledge for the ASP.NET world.
Add to Technorati Favorites


ASP Insider Follow Me On Twitter
Creating a Background Thread When the Web Site First Starts

There have been several instances along the way where a Web application I am developing would be served by having a thread periodically spin up to perform a needed task at a specified interval. For example the application may need to log the state of some variables every hour on the hour or perform an update against a database. I have found there are two ways to set this in motion, through the Application_Start event handler in the Global.asax file or by creating a custom httpModule. Either way the same worker method can be called to perform the needed task.

Creating a Background Thread in the Application_Start Method

<%@ Application Language="VB" %>

<%@ Import Namespace ="System.Threading" %>

<script runat="server">

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)

Dim t As New Thread(AddressOf WriteLog)

t.Start()

End Sub

Public Shared Sub WriteLog()

While 1

My.Computer.FileSystem.WriteAllText( _

HttpContext.Current.Request.ApplicationPath & "\log.txt", _

String.Format("Current Time {0}" & vbCrLf, Now), True)

Thread.Sleep(10000)

End While

End Sub

</script>

This is pretty cut and dry, but for more hard core programmers a custom httpModule is the way to go. A module can be compiled in a class library and used across multiple projects pretty easily. Also when the code is updated it can quickly be replicated across each Web application.

Imports Microsoft.VisualBasic

Imports System.Threading

 

Public Class ExBackGround

    Implements IHttpModule

 

    Public sRoot As String

    Private _context As System.Web.HttpApplication

 

    Public Sub Dispose() Implements System.Web.IHttpModule.Dispose

 

    End Sub

 

    Public Sub Init(ByVal context As System.Web.HttpApplication) _

        Implements System.Web.IHttpModule.Init

        _context = context

        sRoot = context.Request.ApplicationPath

 

        Dim t As New Thread(AddressOf WriteLog)

        t.Start()

 

    End Sub

 

    Public Sub WriteLog()

 

        While 1

 

            My.Computer.FileSystem.WriteAllText( _

            sRoot & "\log.txt", String.Format( _

                "Current Time {0}" & vbCrLf, Now), True)

            Thread.Sleep(10000)

 

        End While

 

    End Sub

End Class

Without getting into the details of setting up a custom httpModule I will draw your attention to the Init method. In this method I create a new Thread, passing it the name of the callback method, WriteLog in this case, to be executed by the thread.

The WriteLog method simply logs the current time to a text file every 10 seconds. Remember the Thread.Sleep method takes the number of milliseconds the thread is supposed to be suspended before further operations are continued. In this case I use a simple While 1 loop for a continuous operation. This will cause the function to never end as long as the Web site is active on the server.

I have found that I can use this technique to call third party databases and Web services to perform background data updates, saving the need for a manual process.

Of course do not forget to register the custom httpModule in the web.config file. This is done with an add element in the httpModules element of the system.web section of the config file.

<httpModules>

   <add type="ExBackGround" name="ExBackGround"/>

</httpModules>

kick it on DotNetKicks.com
Posted: Sunday, September 02, 2007 12:51 PM

by Chris Love
Filed under: ,

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# September 9, 2007 1:37 AM

Chris Love's Official Blog - Professional ASP.NET said:

Trolling the ASP.NET forums this afternoon I came across this thread about creating a custom httpHandler

# August 4, 2008 7:47 PM

Saravanan said:

Hi, I've few questions in your http module implementation.. 1. I'm not seeing any subscription to any of the asp.net events for the Http module to get a chance to process the request. So howz that happening only one time i.e, at the application start? 2. I'm thinking that the registered modules will be given a chance to process each & every http request, in which case how only one thread is active at any point of time. I'm a begineer in this area. Thanks, Saravanan
# August 8, 2008 3:09 AM

Chris Love said:

Saravanan,

You are right this only kicks off the thread the first time the module is invoked. The demo is to show the mechanism to kick off a thread that will run in the background as long as the application (web site) is alive. I have used this technique to synchronize with external databases, grab data periodically from external web services, etc. There is no need to do these operations each time a page is requested. Instead I put the thread to sleep for a specified period of time, say an hour or 6.

# August 8, 2008 5:09 PM

Oscar Velasco said:

Hi Chris, I'm trying to create a background process to update a database and your code was great from that. But now what I need is the ability to log into the application during the day and verify if the thread is already running or not with the intention of trigger it in case is not running and also create a way to stop the thread if for any reason I have to, without deactivating the Web Site in the server. Do you know any way to do this? Is there any way to id the thread with a fixed name that could be called later? Tks, Oscar
# May 1, 2009 11:18 AM

Apadaydreaw said:

Most recent information about County historical map missouri stone topographical and Paulding county here http://county.goodnano-av.com/
# October 3, 2009 3:41 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS