c# - How to prevent a custom thread crashing the windows service in .Net 4.5? -
consider following snippet. thread spawned main windows service thread crash because tries open null path. crashing of windows service follow.
namespace threadcrashservice { class program { public const string servicename = "threadcrashservicetest"; private static timer _timer = null; private static int _timerinterval = 60000; static void main(string[] args) { if (!environment.userinteractive) { // running service using (var service = new service1()) system.serviceprocess.servicebase.run(service); } else { string parameter = string.concat(args); switch (parameter) { case "--install": if (isserviceinstalled()) { uninstallservice(); } installservice(); break; case "--uninstall": if (isserviceinstalled()) { uninstallservice(); } break; default: program program = new program(); program.start(); return; } } } private static void installservice() { managedinstallerclass.installhelper(new[] { assembly.getexecutingassembly().location }); } private static bool isserviceinstalled() { return system.serviceprocess.servicecontroller.getservices().any(s => s.servicename == servicename); } private static void uninstallservice() { managedinstallerclass.installhelper(new[] { "/u", assembly.getexecutingassembly().location }); } public void start() { try { thread thread = new thread(() => threadmethodthatwillcrash()); thread.start(); } catch { // nothing } } public void threadmethodthatwillcrash() { // argumentnullexception file.open(null, filemode.open); } }
}
i know in windows form application, can use
system.windows.application.current.dispatcherunhandledexception += current_dispatcherunhandledexception;
and
system.windows.forms.application.threadexception += new threadexceptioneventhandler(application_threadexception);
to catch global exceptions not handled ui threads. console application, can use
appdomain.currentdomain.unhandledexception += new unhandledexceptioneventhandler(myhandler);
to log exception. not able prevent thread crashing windows service. else can prevent thread crashing windows service? can't change way how thread created because it's in third-party library.
you can use main thread spool tasks tpl in order preserve state of process.
https://stackoverflow.com/a/27384788/376550
https://msdn.microsoft.com/en-us/library/dd537609(v=vs.110).aspx
Comments
Post a Comment