【发布时间】:2015-07-23 22:17:23
【问题描述】:
考虑以下sn-p。主 Windows 服务线程产生的线程将崩溃,因为它试图打开一个空路径。随之而来的是windows服务的崩溃。
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);
}
}
}
我知道在windows窗体应用中,我们可以使用
System.Windows.Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
和
System.Windows.Forms.Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
捕获未由 UI 线程处理的全局异常。但是对于控制台应用,我们只能使用
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
记录异常。但这并不能防止线程崩溃 windows 服务。我还能做些什么来防止线程崩溃 Windows 服务?我无法更改线程的创建方式,因为它在第三方库中。
【问题讨论】:
标签: c# .net multithreading windows-services