I want to handle when windows service is killed by task manager or by system restart.
I tried using below handler inside Timer_Elapsed method of the service timer
public void Start() { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; _myTimer= new Timer(10000); _myTimer.Elapsed += OnElapsed; _myTimer.AutoReset = false; _myTimer.Start(); } private void OnElapsed(object sender, ElapsedEventArgs e) { try { _myTimer.Stop(); //Work } finally { _myTimer.Start(); } }
and even I have placed the same into Main() method of the console as I am using Topshelf for windows service.
static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; var exitCode = HostFactory.Run(hostConfigurator => { hostConfigurator.Service<MyService>(serviceConfigurator => { serviceConfigurator.ConstructUsing(() => new MyService()); serviceConfigurator.WhenStarted(MyService => MyService.Start()); serviceConfigurator.WhenStopped(MyService=> MyService.Stop()); }); hostConfigurator.RunAsLocalSystem(); hostConfigurator.SetDisplayName("MyService"); hostConfigurator.SetDescription("MyService"); hostConfigurator.SetServiceName("MyService"); hostConfigurator.UseLog4Net(); }); } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { File.AppendAllText(@"C:\Crash.txt", "Main Termination"); }
In either scenario the handler is not getting called when I kill the windows service process from task manager or system restart. Even TopShelf is not logging "UnhandledServiceException" exit code.
I have searched for all possible ways but no luck. Could any one please help me in this.
Thanks