Sometimes it is necessary that a service work next to an asp.net application, which would send out mail or simply do some operations at certain intervals. This can be done using windows service, but not all hosting systems allow you to install them and it is not very convenient to debug them (for my taste). I found in the network an interesting way to do without the service and I want to share it. Perhaps this is a well-known thing, but in the search I found nothing about it.
The idea is to put an object into the cache when the application starts, and when it “dies” repeat the procedure again. We do this in global.asax. Simplified, the code will look like this: protected void Application_Start(object sender, EventArgs e) {
HttpContext.Current.Cache.Add("ServiceCacheKey", "Dummy", null, DateTime.MaxValue, TimeSpan.FromMinutes(1), CacheItemPriority.Normal, new CacheItemRemovedCallback(CacheItemRemovedCallback));
}
')
Now, in CacheItemRemovedCallbak itself, you can do the necessary “service” actions and start the process of placing an object into the cache. Since at this moment HttpContext is not available, we will call up some page, and at the moment of calling this page put the object in the cache.
public void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason) {
//do service work
WebClient wc = new WebClient(); wc.DownloadData(SecretPageURL); }
That's all. The only thing that confuses me is that now for each request there will be a check on whether the necessary page has been called up and whether it is necessary to put the “service” object in the cache - I do not know how this will affect the performance.