【发布时间】:2016-05-16 19:55:40
【问题描述】:
我创建了一个 Windows 服务应用程序。它根据 app.config 文件中包含的应用程序设置运行。它将同时安装在不同的位置(网络、PC)。每个位置都需要在 app.config 文件中设置自己的参数。所以我不希望它在安装后自动运行。通过这样做,每个位置用户都可以打开配置文件并对其进行更改。然后他们可以启动服务。但在那之后,该服务将永远运行。即使他们重新启动Windows,它也会在Windows打开后自动运行。
这是我的安装程序类。安装后不会自动运行。那挺好的。但是如果我手动运行它并重新启动PC,当重新启动完成时,它仍然等待手动启动。我该怎么办?
public partial class MyServiceInstaller : System.Configuration.Install.Installer
{
ServiceInstaller _serviceInstaller = new ServiceInstaller();
ServiceProcessInstaller _processInstaller = new ServiceProcessInstaller();
string _serviceName = "MyService";
string _displayName = "My Service";
string _description = "My Service - Windows Service";
public MyServiceInstaller()
{
InitializeComponent();
this.BeforeInstall += new InstallEventHandler(MyServiceInstaller_BeforeInstall);
_processInstaller.Account = ServiceAccount.LocalSystem;
_serviceInstaller.StartType = ServiceStartMode.Automatic;
_serviceInstaller.Description = _description;
_serviceInstaller.ServiceName = _serviceName;
_serviceInstaller.DisplayName = _displayName;
Installers.Add(_serviceInstaller);
Installers.Add(_processInstaller);
}
protected override void OnCommitted(System.Collections.IDictionary savedState)
{
ServiceController sc = new ServiceController(_serviceName);
if (sc.Status != ServiceControllerStatus.Running)
{
TimeSpan timeout = TimeSpan.FromMilliseconds(10000);
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running, timeout);
sc.Stop();
}
else
{
RestartService(10000);
}
}
private void RestartService(int timeoutMiliseconds)
{
ServiceController service = new ServiceController(_serviceName);
int millisec1 = Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMiliseconds);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
int millisec2 = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(timeoutMiliseconds - (millisec2 - millisec1));
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
void MyServiceInstaller_BeforeInstall(object sender, System.Configuration.Install.InstallEventArgs e)
{
List<ServiceController> services = new List<ServiceController>(ServiceController.GetServices());
foreach (ServiceController s in services)
{
if (s.ServiceName == this._serviceInstaller.ServiceName)
{
ServiceInstaller ServiceInstallerObj = new ServiceInstaller();
ServiceInstallerObj.Context = new System.Configuration.Install.InstallContext();
ServiceInstallerObj.Context = Context;
ServiceInstallerObj.ServiceName = _serviceName;
ServiceInstallerObj.Uninstall(null);
}
}
}
}
【问题讨论】:
-
您的代码似乎将启动类型设置为自动。您能否检查事件日志以查看您的服务是否正在尝试自动启动,但失败了。如果您的服务依赖于另一个尚未启动的服务,就会发生这种情况。
-
@sgmoore 感谢您的评论。我意识到我的代码依赖于其他一些代码,这些代码需要等待一段时间才能在重新启动后执行。请写下这个作为答案,我会标记它。
标签: c# windows-services