如何在发生未经处理的异常后重新启动 Windows 服务
本文关键字:异常 重新启动 服务 Windows 处理 | 更新日期: 2023-09-27 17:56:26
我有一个控制台应用程序,它是一个FTP服务器。此控制台应用程序工作正常。现在,我想使用Windows服务运行此FTP服务器。
我有一个未处理的异常陷阱,它捕获了未经处理的异常。发生此异常后,我想停止服务,破坏 FTP 服务器的类,将其延迟 10 秒并重新启动服务。
以下是我的代码(如果没有未经处理的异常,ftp 服务器和服务工作正常,但我想成功停止并重新启动服务。此代码可以正常停止服务,但不会重新启动它)。有什么想法吗?
public partial class FTPService : ServiceBase
{
private static FtpServer _ftpServer;
public FTPService(string[] args)
{
InitializeComponent();
string eventSourceName = "Ftp Server Events";
eventLog1 = new System.Diagnostics.EventLog();
string logName = "Ftp Server Log";
if (args.Count() > 0)
{
eventSourceName = args[0];
}
if (args.Count() > 1)
{
logName = args[1];
}
eventLog1 = new System.Diagnostics.EventLog();
if (!System.Diagnostics.EventLog.SourceExists(eventSourceName))
{
System.Diagnostics.EventLog.CreateEventSource(eventSourceName, logName);
}
eventLog1.Source = eventSourceName;
eventLog1.Log = logName;
if (!System.Diagnostics.EventLog.SourceExists("Ftp Server Events"))
{
System.Diagnostics.EventLog.CreateEventSource(
"Ftp Server Events", "Ftp Server Log");
}
this.ServiceName = "FTP Service";
this.AutoLog = true;
}
public static void Main(string[] args)
{
ServiceBase.Run(new FTPService(new string[0]));
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
var database = new Database(); // Gets database details as FTP server tals to database.
var configurationManager = new ConfigurationManagerWrapper(); // Same as above
_ftpServer = new FtpServer(new Assemblies.Ftp.FileSystem.StandardFileSystemClassFactory(database, configurationManager));
_ftpServer.Start(); //Starts the service (FTP Server works fine if there is no handled exception)
eventLog1.WriteEntry("Started");
FtpServerMessageHandler.Message += MessageHandler_Message;
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
}
protected override void OnStop()
{
_ftpServer.Stop(); // This calls the destructor for FTP Server, to close any TCP Listening connections, etc
base.OnStop(); // Here I stop the service itself.
eventLog1.WriteEntry("Stopped");
Thread.Sleep(10000);
}
protected void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) // unhandled exception handler
{
eventLog1.WriteEntry(e.ExceptionObject.ToString());
Thread.Sleep(5000);
OnStop(); // Calls onstop which stops FTP Server and destroys previous objects of FTP server
var serviceMgr = new ServiceController();
serviceMgr.Start(); // Here I want to restart the service (it doesn't work)
}
}
尝试以下操作:
services.msc -> 您的服务>属性 ->恢复
为您设置属性
-> 保存 ->您的服务 ->重新启动