定时Job在IIS中潜在危险-IIS 定期回收
引言
有时我们会在IIS中启用一些定时服务,但是你必须清楚IIS会定期回收Asp.net的应用程序的。首先来看IIS啥时候回收APPDomain.
APPDomain 回收时机
There are several things that can cause ASP.NET to tear down your AppDomain.
- When you modify web.config, ASP.NET will recycle the AppDomain, though the w3wp.exe process (the IIS web server process) stays alive.
- IIS will itself recycle the entire w3wp.exe process every 29 hours. It’ll just outright put a cap in the w3wp.exe process and bring down all of the app domains with it.
- In a shared hosting environment, many web servers are configured to tear down the application pools after some period of inactivity. For example, if there are no requests to the application within a 20 minute period, it may take down the app domain.
If any of these happen in the middle of your code execution, your application/data could be left in a pretty bad state as it’s shut down without warning.
So why isn’t this a problem for your typical per request ASP.NET code?
When ASP.NET tears down the AppDomain, it will attempt to flush the existing requests and give them time to complete before it takes down the App Domain. ASP.NET and IIS are considerate to code that they know is running,such as code that runs as part of a request.
Problem is, ASP.NET doesn’t know about work done on a background thread spawned using a timer or similar mechanism. It only knows about work associated with a request.
有哪些风险
There are three main risks, one of which I’ll focus on in this blog post.
- An unhandled exception in a thread not associated with a request will take down the process. This occurs even if you have a handler setup via the Application_Error method. I’ll try and explain why in a follow-up blog post, but this is easy to deal with.
- If you run your site in a Web Farm, you could end up with multiple instances of your app that all attempt to run the same task at the same time. A little more challenging to deal with than the first item, but still not too hard. One typical approach is to use a resource common to all the servers, such as the database, as a synchronization mechanism to coordinate tasks.
- The AppDomain your site runs in can go down for a number of reasons and take down your background task with it. This could corrupt data if it happens in the middle of your code execution.
告诉ASP.NET ,我还在运行
The good news is there’s an easy way to tell ASP.NET about the work you’re doing! In the System.Web.Hosting namespace, there’s an important class,HostingEnvironment. According to the MSDN docs, this class…
Provides application-management functions and application services to a managed application within its application domain
This class has an important static method, RegisterObject
. The MSDN description here isn’t super helpful.
Places an object in the list of registered objects for the application.
For us, what this means is that the RegisterObject
method tells ASP.NET that, “Hey! Pay attention to this code here!” Important! This method requires full trust!
This method takes in a single object that implements the IRegisteredObject
interface. That interface has a single method:
public interface IRegisteredObject
{
void Stop(bool immediate);
}
When ASP.NET tears down the AppDomain, it will first attempt to call Stop
method on all registered objects.
In most cases, it’ll call this method twice, once with immediate
set to false.
This gives your code a bit of time to finish what it is doing. ASP.NET gives all instances of IRegisteredObject
a total of 30 seconds to complete their work, not 30 seconds each. After that time span, if there are any registered objects left, it will call them again with immediate
set to true.
This lets you know it means business and you really need to finish up pronto! I modeled my parenting technique after this method when trying to get my kids ready for school.
When ASP.NET calls into this method, your code needs to prevent this method from returning until your work is done. Levi showed me one easy way to do this by simply using a lock. Once the work is done, the code needs to unregister the object.
For example, here’s a simple generic implementation of IRegisteredObject
. In this implementation, I simply ignored the immediate
flag and try to prevent the method from returning until the work is done. The intent here is I won’t pass in any work that’ll take too long. Hopefully.
public class JobHost : IRegisteredObject
{
private readonly object _lock = new object();
private bool _shuttingDown; public JobHost()
{
HostingEnvironment.RegisterObject(this);
} public void Stop(bool immediate)
{
lock (_lock)
{
_shuttingDown = true;
}
HostingEnvironment.UnregisterObject(this);
} public void DoWork(Action work)
{
lock (_lock)
{
if (_shuttingDown)
{
return;
}
work();
}
}
}
I wanted to get the simplest thing possible working. Note, that when ASP.NET is about to shut down the AppDomain, it will attempt to call the Stop
method. That method will try to acquire a lock on the _lock
instance. The DoWork
method also acquires that same lock. That way, when the DoWork
method is doing the work you give it (passed in as a lambda) the Stop
method has to wait until the work is done before it can acquire the lock. Nifty.
Later on, I plan to make this more sophisticated by taking advantage of using aTask
to represent the work rather than an Action
. This would allow me to take advantage of task cancellation instead of the brute force approach with locks.
With this class in place, you can create a timer on Application_Start
(I generally use WebActivator to register code that runs on app start) and when it elapses, you call into the DoWork
method here. Remember, the timer must be referenced or it could be garbage collected.
Here’s a small example of this:
using System;
using System.Threading;
using WebBackgrounder; [assembly: WebActivator.PreApplicationStartMethod(
typeof(SampleAspNetTimer), "Start")] public static class SampleAspNetTimer
{
private static readonly Timer _timer = new Timer(OnTimerElapsed);
private static readonly JobHost _jobHost = new JobHost(); public static void Start()
{
_timer.Change(TimeSpan.Zero, TimeSpan.FromMilliseconds(1000));
} private static void OnTimerElapsed(object sender)
{
_jobHost.DoWork(() => { /* What is it that you do around here */ });
}
}
建议
This technique can make your background tasks within ASP.NET much more robust. There’s still a chance of problems occurring though. Sometimes, the AppDomain goes down in a more abrupt manner. For example, you might have a blue screen, someone might trip on the plug, or a hard-drive might fail. These catastrophic failures can take down your app in such a way that leaves data in a bad state. But hopefully, these situations occur much less frequently than an AppDomain shutdown.
Many of you might be scratching your head thinking it seems weird to use a web server to perform recurring background tasks. That’s not really what a web server is for. You’re absolutely right. My recommendation is to do one of the following instead:
- Write a simple console app and schedule it using Windows task schedule.
- Write a Windows Service to manage your recurring tasks.
- Use an Azure worker or something similar.
Given that those are my recommendations, why am I still working on a system for scheduling recurring tasks within ASP.NET that handles web farms and AppDomain shutdowns I call WebBackgrounder (NuGet package coming later)?
I mean, besides the fact that I’m thick-headed? Well, for two reasons.
The first is to make development easier. When you get latest from our source code, I just want everything to work. I don’t want you to have to set up a scheduled task, or an Azure worker, or a Windows server on your development box. A development environment can tolerate the issues I described.
The second reason is for simplicity. If you’re ok with the limitations I mentioned, this approach has one less moving part to worry about when setting up a website. There’s no need to configure an external recurring task. It just works.
But mostly, it’s because I like to live life on the edge.
参考
The Dangers of Implementing Recurring Background Tasks In ASP.NET
https://github.com/NuGet/WebBackgrounder
Use IIS Application Initialization for keeping ASP.NET Apps alive
定时Job在IIS中潜在危险-IIS 定期回收的更多相关文章
- 在IIS中实现JSP
在IIS中实现JSP IIS本身是不可以支持JSP页面的,但是随着JAVA技术的广泛应用,越来越多的网站采用JAVA技术编写程序,我们根据一些资料和自己的实践经验总结了以下两种JAVA应用服务器 ...
- Quartz.net 定时任务在IIS中未按时执行
IIS 垃圾回收机制下解决Quartz.net 的不执行问题 IIS中涉及了垃圾回收机制,quartz.net 在ASP.NET 项目中可以实现线程监控定时执行任务,但是在IIS7.5机一下版本中涉及 ...
- Quartz.net 定时任务在IIS中没有定时执行
问题:Quartz.net 定时任务在项目部署到IIS中发现没有定时执行 解决方案: 1.在服务器上装一个360(自带自动刷新功能),在工具——>自动刷新——>自动刷新勾上 然后再设置一下 ...
- 从客户端中检测到有潜在危险的Request.Form值的解决办法
http://www.pageadmin.net/article/20141016/935.html 如果你网站iis服务器asp.net采用了4.0的版本,则默认会阻止客户端的html内容提交,提交 ...
- IIS中的上传目录权限设置问题
虽然 Apache 的名声可能比 IIS 好,但我相信用 IIS 来做 Web 服务器的人一定也不少.说实话,我觉得 IIS 还是不错的,尤其是 Windows 2003 的 IIS 6(马上 Lon ...
- IIS中启用ASP并连接Access数据库的解决办法
1. IIS安装ASP模块 进入控制面板 ---- 打开或关闭Windows功能 选择如下所示两项,点击安装完成 2. 打开父路径许可 选择相应应用程序池 ----- 高级设置 ---- 将“启用父路 ...
- 关于 IIS 中 Excel 访问的问题
关于 IIS 上 Excel 文件的访问, 一路上困难重重, 最后按以下步骤进行设置, 可在 IIS 中正常使用! 1. 引用及代码: 1). 项目中添加 Excel 程序集引用(注意: 从系统 CO ...
- 【续集】在 IIS 中部署 ASP.NET 5 应用程序遭遇的问题
dudu 的一篇博文:在 IIS 中部署 ASP.NET 5 应用程序遭遇的问题 针对 IIS 部署 ASP.NET 5 应用程序的问题,在上面博文中主要采用两种方式尝试: VS2015 的 Publ ...
- 【记录】从客户端()中检测到有潜在危险的 Request.Path 值。
从客户端()中检测到有潜在危险的 Request.Path 值. 错误信息: Application_Error Url: www.cnblogs.com/%E5%BA%.... UserAgent: ...
随机推荐
- Ubuntu下使用nvm
写在前面:刚写着写着博客就跨年了,希望新的一年大家万事如意,一切向"前"看! 安装 wget -qO- https://raw.githubusercontent.com/crea ...
- H5单页面手势滑屏切换原理
H5单页面手势滑屏切换是采用HTML5 触摸事件(Touch) 和 CSS3动画(Transform,Transition)来实现的,效果图如下所示,本文简单说一下其实现原理和主要思路. 1.实现原理 ...
- 使用CSS3实现一个3D相册
CSS3系列我已经写过两篇文章,感兴趣的同学可以先看一下CSS3初体验之奇技淫巧,CSS3 3D立方体效果-transform也不过如此 第一篇主要列出了一些常用或经典的CSS3技巧和方法:第二篇是一 ...
- MVC5+EF6+MYSQl,使用codeFirst的数据迁移
之前本人在用MVC4+EF5+MYSQL搭建自己的博客.地址:www.seesharply.com;遇到一个问题,就是采用ef的codefirst模式来编写程序,我们一般会在程序开发初期直接在glob ...
- jquery插件的用法之cookie 插件
一.使用cookie 插件 插件官方网站下载地址:http://plugins.jquery.com/cookie/ cookie 插件的用法比较简单,直接粘贴下面代码示例: //生成一个cookie ...
- setCapture、releasCapture 浅析
1. setCapture 简介 setCapture可以将鼠标事件锁定在指定的元素上,当元素捕获了鼠标事件后,该事件只能作用在当前元素上. 以下情况会导致事件锁定失败: 当窗口失去焦点时,锁定的事件 ...
- Ajax使用WCF实现小票pos机打印源码
通过ajax跨域方式调用WCF服务,实现小票pos机的打印,源码提供web方式,客户端方式测试,服务驻留右侧底部任务栏,可控制服务开启暂停,用户可自定义小票打印模板,配合零售录入. qq 22945 ...
- JQuery阻止事件冒泡
冒泡事件就是点击子节点,会向上触发父节点,祖先节点的点击事件. 我们在平时的开发过程中,肯定会遇到在一个div(这个div可以是元素)包裹一个div的情况,但是呢,在这两个div上都添加了事件,如果点 ...
- 类型转换器(InitBinder 初始化绑定器)
单日期格式 导入jar包 创建FirstController.java @Controller public class FirstController { /** * @param binder * ...
- 钉钉开放平台demo调试异常问题解决:hostname in certificate didn't match
今天研究钉钉的开放平台,结果一个demo整了半天,这帮助系统写的也很难懂.遇到两个问题: 1.首先是执行demo时报unable to find valid certification path to ...