我希望在任务管理器或系统重启时终止Windows服务。
我尝试在服务计时器
的Timer_Elapsed方法中使用下面的处理程序 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();
}
}
甚至我把它放在控制台的Main()方法中,就像我使用Topshelf for windows服务一样。
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");
}
在任一场景中,当我从任务管理器或系统重启中终止Windows服务进程时,不会调用处理程序。甚至TopShelf也没有记录“UnhandledServiceException”退出代码。
我搜索过Google所有可行的方法,但没有运气。任何人都可以帮助我。
由于