views:

393

answers:

6
+1  Q: 

ASP.NET and Timers

Consider this code...

using System.Threading;
//...
Timer someWork = new Timer(
    delegate(object state) {
        //Do some work here...
    },
    null, 0, 60000);

HttpContext.Current.Application["SomeWorkItem"] = someWork;

Could this be dangerous? Caching a timer in the Application to perform some work in the background while your site runs seems safe, but I wondered if anyone has some experience with this.

I'm sure that writing a Service to run in the background would certainly be much better, but sometimes that isn't always an option. Is this an alternative?

+3  A: 

The problem with this is that you are not guaranteed the process still being alive. IIS will reclaim the process basically whenever it feels like it, so you run the risk of it not being performed.

If you need this work done then you need to either code it into a web call, or have a service running in the background of the server.

Stephen Wrighton
+1  A: 

That would be dangerous as there can be times when the worker process gets recycled or the AppDomain crashes and the Work Item is killed and you may want it to recover what it was doing, it may not be possible.

A Windows service may be OK if you can get that work item out into a service. If an HttpContext is required for the work though you may want to have a windows service call a webservice to do the call periodically that may work though likely not ideal.

JB King
A: 

That makes sense, but just for fun, what if the work doesn't need to run if the site gets shut down? If it's associated with the Application_Start event and only needs to run while people are browsing the site, what are the risks at that point?

Good answers, I'm just curious a little more about how that works on the inside.

Hugoware
A: 

I would recommend you setup a scheduled task to run a page on your site. I usually point the scheduled task to a .vbs file with the following:

On Error Resume Next
Dim objRequest
Dim URL

Set objRequest = CreateObject("Microsoft.XMLHTTP")
URL = "http://www.mywebsite.com/cron/pagetorun.ashx"

objRequest.open "POST", URL , false

objRequest.Send

Set objRequest = Nothing
Arthur Chaparyan
+3  A: 

This would generally be a bad idea, as System.Threading.Timer uses threads from the ThreadPool, the same as ASP.Net.

If for what ever reason your timer delegate blocks or stops, the timer will simply begin a new Thread after the timeout period, which eats in to the Threads available for ASP.net.

If they all begin blocking, effectively you will not be able to serve any more web requests (probably a bad thing)

Xian
A: 

Omar Al Zabir has an excellent post on using cache item callbacks for this purpose.

http://www.codeproject.com/KB/aspnet/ASPNETService.aspx?fid=229682&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=76&select=1334820