1

I have a library class used in ASP.Net and non-web applications that needs end-of-application finalization.

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.

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. And Global.Application_End is specific to 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.

(see http://msdn.microsoft.com/en-us/library/ms172133.aspx)

John Saunders
  • 160,644
  • 26
  • 247
  • 397
BrianCooksey
  • 1,543
  • 1
  • 12
  • 19
  • In a class library that's shared? – Mike Perrenoud Nov 13 '13 at 13:10
  • 1
    You can't guard against every contingency - at the end of the day, someone might walk over to the machine and pull its plug out of the wall - having the library *consumer* indicate when they've finished using the library (in either Application_End or wherever makes sense for a non-web application) is going to be a cleaner overall solution than trying to "magically" detect shutdown scenarios. – Damien_The_Unbeliever Nov 13 '13 at 13:17
  • Yes, this is a shared library. – BrianCooksey Nov 13 '13 at 14:24
  • Not worried about "every" contingency - looking for the standard set of process/application end/exit scenarios. – BrianCooksey Nov 13 '13 at 14:24
  • I've posted an answer that works below, but I'm interested in other workable solutions as well. – BrianCooksey Nov 13 '13 at 15:09

1 Answers1

1

It appears that a simulated static fianalizer described in this S.O. answer, https://stackoverflow.com/a/256278/449837, works in both web and non-web applications.

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)

Community
  • 1
  • 1
BrianCooksey
  • 1,543
  • 1
  • 12
  • 19