.net - How to get event/exception from timer event handler back to main thread in C#? -
i have windows service application (no winforms). in main method started timer. timer elapsed event handler running in new thread(?). easy way how throw exceptions timer elapsed event handler main thread?
i trying handle exceptions in handler body , rise custom events, when restart main process on rising event, runs 2 processes doing same things simultaneously.
how can event or exception information form timer event handler thread main thread?
thank you.
edit:
using system; using system.security.permissions; using system.timers; namespace testingconsoleapplication.model { static class threadexceptiontester { [securitypermission(securityaction.demand, flags = securitypermissionflag.controlappdomain)] public static void run() { appdomain currentdomain = appdomain.currentdomain; currentdomain.unhandledexception += new unhandledexceptioneventhandler(myhandler); timer timer = new timer(1000); timer.elapsed += new elapsedeventhandler(timereventhandler); timer.start(); try { throw new exception("1"); } catch (exception e) { console.writeline("catch clause caught : " + e.message); } //throw new exception("2"); } static void myhandler(object sender, unhandledexceptioneventargs args) { exception e = (exception)args.exceptionobject; console.writeline("myhandler caught : " + e.message); } static void timereventhandler(object source, elapsedeventargs e) { console.writeline("throwing timer event handler"); throw new exception("timer exception"); } } } this write on console this:
catch clause caught : 1 throwing timer event handler and program crash unhandled exception on throw new exception("timer exception"); if uncomment throw new exception("2"); exeption processed , on console "catch clause caught : 2". in other words, timer exceptions not processed myhandler.
you need use appdomain.unhandledexception event subscribing exception events.
edit: according msdn:
in .net framework version 2.0 , earlier, timer component catches , suppresses exceptions thrown event handlers elapsed event. behavior subject change in future releases of .net framework.
i have looked source of system.timers.timer .net4 using dotpeek , there still no changes since 2.0, consider using system.threading.timer instead.
Comments
Post a Comment