我在处理Windows服务方面还比较新,但我发现了一个奇怪的问题,希望能得到一些澄清。我有一个用C#编写的Windows服务,我使用命令行安装和启动它(在stackoverflow上找到了很好的说明)。我的服务的主要方法如下:
static void Main(string[] args)
{
if (args.Length == 0)
{
ServiceBase.Run(new MyServiceName());
}
else if (args.Length == 1)
{
const string name = "MyServiceName";
Type type = typeof(MyAssembly);
switch (args[0])
{
case "-install":
ServiceUtils.InstallService(name, type);
ServiceUtils.StartService(args, name);
break;
case "-uninstall":
ServiceUtils.StopService(name);
ServiceUtils.UninstallService(name, type);
break;
default:
throw new NotImplementedException();
}
}
}
当我调试时,我总是向应用程序发送一个参数(-install)。因此,第一个if语句(if (args.Length == 0))永远不会执行。这是预期的,我的服务已经成功安装和启动。然而,如果我删除该if语句并只保留if (args.Length == 1)语句,则我的服务可以正确安装但无法启动,并出现以下错误:
“在计算机“。”上无法启动MyServiceName。”
我的问题是:为什么在我的应用程序中从未执行第一个if语句的代码是必需的?
以下是InstallService和StartService方法的支持代码(也是我从stackoverflow获取的):
public static void InstallService(string serviceName, Type t)
{
if (IsInstalled(serviceName)) return;
try
{
Assembly a = t.Assembly;
using (AssemblyInstaller installer = GetInstaller(a))
{
IDictionary state = new Hashtable();
try
{
installer.Install(state);
installer.Commit(state);
}
catch
{
try
{
installer.Rollback(state);
}
catch
{ }
throw;
}
}
}
catch
{
throw;
}
}
public static void StartService(string[] args, string serviceName)
{
if (!IsInstalled(serviceName)) return;
Console.WriteLine("Service is installed. Attempting to start service.");
ServiceController sc = new ServiceController();
sc.ServiceName = serviceName;
if (sc.Status == ServiceControllerStatus.Stopped)
{
Console.WriteLine("Starting {0}: ", sc.ServiceName);
try
{
sc.Start(args);
sc.WaitForStatus(ServiceControllerStatus.Running);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
ServiceBase.Run()
才能使服务正常工作,并且您不希望在任何其他情况下调用它。 - Andrew Barber