c# - Finally is not executed when in a Thread running in a Windows Service -
can explain why block not executed? have read posts when expect block not executed, seems case. code needs topshelf , log4net. running .net 4.5
i guess must windows service engine kicks in on unhandled exceptions, why running before block has finished?
using log4net; using log4net.config; using system; using system.threading; using topshelf; namespace consoleapplication1 { public class hostmain { static void main(string[] args) { hostfactory.run(x => { x.service<hostmain>(s => { s.constructusing(name => new hostmain()); s.whenstarted(tc => tc.start()); s.whenstopped(tc => tc.stop()); }); x.runaslocalsystem(); x.setservicename("timertest"); }); } public void stop() { logmanager.getlogger("mylog").info("stopping"); } public void start() { xmlconfigurator.configure(); logmanager.getlogger("mylog").info("starting"); new thread(startservicecode).start(); } public void startservicecode() { try { logmanager.getlogger("mylog").info("throwing"); throw new applicationexception(); } { logmanager.getlogger("mylog").info("finally"); } } } }
outputs
starting throwing stopping
edit: please comment why downgrading, maybe don't understand problem? see big problem here. write domain logic important stuff in clause on exception. if host logic in windows service design broken.
from mdsn try-finally (c# reference)
within handled exception, associated finally block guaranteed run. however, if exception unhandled, execution of block dependent on how exception unwind operation triggered. that, in turn, dependent on how computer set up. more information, see unhandled exception processing in clr.
usually, when unhandled exception ends application, whether or not block run not important
this design, .net has chosen terminate application, reason is, there terribly wrong, didn't work expected, calling finally, don't want more damage, best end application.
what if throws 1 more exception, go? if application close, may have closed or started closing managed resources , accessing them logging in turn out fatal well.
Comments
Post a Comment