[英]In C#, how can a class do its own application-end finalization in a way that works under both ASP.Net and non-web applications?
I have a library class used in ASP.Net and non-web applications that needs end-of-application finalization. 我有一个在ASP.Net和非Web应用程序中使用的库类,它们需要对应用程序结束进行终结处理。
Within my project's library, I want the class to do its own end-of-application finalization without requiring a developer to add a call to Global.Application_End or AppDomain.CurrentDomain.ProcessExit. 在我的项目的库中,我希望类进行自己的应用程序终结处理,而无需开发人员添加对Global.Application_End或AppDomain.CurrentDomain.ProcessExit的调用。
How can this be done? 如何才能做到这一点?
Additional background/rationale: 其他背景/理由:
Even if I were to consider those options, it appears that AppDomain.CurrentDomain.ProcessExit does not get called when an ASP .Net application is stopped in IIS. 即使我考虑这些选项,当ASP .Net应用程序在IIS中停止时,AppDomain.CurrentDomain.ProcessExit似乎也没有被调用。 And Global.Application_End is specific to ASP .Net. 并且Global.Application_End特定于ASP .Net。 So, neither option is compatible with both situations. 因此,这两种选择都不兼容。
If it helps to have a specific example of why this might be needed... In this particular case, it uses SqlDependency which (as I understand it) requires a call to SqlDependency.Start for initialization and a call to SqlDependency.Stop before application termination. 如果有一个为什么可能需要这样做的特定示例有帮助...在这种特殊情况下,它使用SqlDependency,据我所知,它需要调用SqlDependency.Start进行初始化,并需要在应用之前调用SqlDependency.Stop。终止。
(see http://msdn.microsoft.com/en-us/library/ms172133.aspx ) (请参阅http://msdn.microsoft.com/en-us/library/ms172133.aspx )
It appears that a simulated static fianalizer described in this SO answer, https://stackoverflow.com/a/256278/449837 , works in both web and non-web applications. 看来,此SO答案https://stackoverflow.com/a/256278/449837中描述的模拟静态fianalizer在Web和非Web应用程序中均可使用。
Here's a sample that I have working: 这是我正在工作的示例:
public class ClassThatNeedsStaticFinalizer {
// ... other class properties, methods, etc ...
#region Static Finalizer Emulation
static readonly Finalizer finalizer = new Finalizer();
private sealed class Finalizer
{
~Finalizer()
{
// ... Do final stuff here ...
}
}
#endregion
}
(NOTE: For some code scratchpad environments like LinqPad, ~Finalizer may not fire until the scratchpad app itself closes) (注意:对于某些代码便签本环境,例如LinqPad,在便签本应用程序本身关闭之前,〜Finalizer可能不会触发)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.