Consider the following snippet. The thread spawned by the main windows service thread will crash because it tries to open a null path. Then the crashing of the windows service will 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 as 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 {
// do nothing
}
}
public void ThreadMethodThatWillCrash() {
// ArgumentNullException
File.Open(null, FileMode.Open);
}
}
}
I know in windows form application, we can use
System.Windows.Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
and
System.Windows.Forms.Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
to catch the global exceptions not handled by UI threads. But for a console application, we can only use
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
to log the exception. But this is not able to prevent the thread crashing the windows service. What else can I do to prevent the thread crashing the windows service? I can't change the way how the thread is created because it's a in a third-party library.