Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .Net exe doesn't close when PC is restarted, keeping the machine from restarting

We have a SmartClient built in C# that stubornly remains open when the PC its running on is being restarted. This halts the restart process unless the user first closes the SmartClient or there is some other manual intervention.

This is causing problems when the infrastructure team remotely installs new software that requires a machine reboot.

Any ideas for getting the SmartClient app to recognize the shutdown/restart event from Windows and gracefully kill itself?

UPDATE: This is a highly threaded application with multiple gui threads. yes, multiple gui threads. Its really a consolidation of many project that in and of themselves could be standalone applications - all of which are launched and managed from a single exe that centralizes those management methods and keeps track of those threads. I don't believe using background threads is an option.

like image 625
ScottCher Avatar asked Oct 03 '08 18:10

ScottCher


2 Answers

OK, if you have access to the app, you can handle the SessionEnded event.

...
Microsoft.Win32.SystemEvents.SessionEnded +=new
  Microsoft.Win32.SessionEndedEventHandler(shutdownHandler);

...

private void shutdownHandler(object sender, Microsoft.Win32.SessionEndedEventArgs e) {
  // Do stuff
}
like image 170
Vincent McNabb Avatar answered Sep 30 '22 01:09

Vincent McNabb


It must be a thread that continues to run preventing your application to close. If you are using threading an easy fix would be to set it to background.

A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.

http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx

like image 21
Catalin DICU Avatar answered Sep 30 '22 02:09

Catalin DICU