equivalent - .NET code execution at normal process exit? -


in c there atexit function, which

the atexit() function registers given function called @ normal process termination, either via exit(3) or via return program's main().

python has similar capability.

does .net provide way call code @ normal process termination? know there things domainunload , processexit, @ least far can tell, these unreliable - either requiring application windows forms (or wpf app), or else. writing code .dll, can't rely on things mucking main program function - wrapping in try/catch.

my ultimate goal perform file cleanup (i.e. flush buffers , close). if can call unmanaged code, e.g. win32api hook or something, i'm fine that.

there no straight-forward answer know of.

if want write robust dll, should prepare several scenarios:

  1. your code hosted in .net application, in default appdomain. (the trivial scenario)
  2. your code hosted in .net application, in appdomain created host's code.
  3. your code hosted in unmanaged application (which hosts clr).

the 3rd scenario hardest deal with, since clr can disabled host, managed code won't execute anymore.

system.windows.forms.application.applicationexit no since applies winform applications.

system.appdomain.domainunload no since never raised default appdomain.

appdomain.processexit no good: if code hosted in separate appdomain, host might unload appdomain, event never raise.

i'd start trying cover cases, using like:

if (appdomain.currentdomain.isdefaultappdomain())     appdomain.currentdomain.processexit += myterminationhandler; else     appdomain.currentdomain.domainunload += myterminationhandler; 

but notice following remark (from msdn):

the total execution time of processexit event handlers limited, total execution time of finalizers limited @ process shutdown. default 2 seconds. unmanaged host can change execution time calling iclrpolicymanager::settimeout method opr_processexit enumeration value.

the above code still leaves 3rd scenario unattended. there 2 methods know of dealing scenario (along first two)

first, can use system.runtime.compilerservices.runtimehelpers.executecodewithguaranteedcleanup method, follows:

{ //  goes @ code's entry point     runtimehelpers.executecodewithguaranteedcleanup(myexecutioncode, mycleanupcode, null); } static void myexecutioncode(object data) { /* execution code here */} static void mycleanupcode(object data, bool exceptionthrown) { /* cleanup code here */ } 

second, can utilize system.runtime.constrainedexecution.criticalfinalizerobject class (see msdn here) inheriting , putting cleanup code in finalizer. requires cleanup code adhere constrained execution region guidelines.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

java - Using an Integer ArrayList in Android -