Tutorial :ASP.NET and Timers



Question:

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?


Solution:1

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)


Solution:2

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.


Solution:3

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.


Solution:4

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.


Solution:5

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  


Solution:6

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »