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

Share This Article With Your Friends!