.NET Windows服务是否需要调用ServiceBase.Run()
||
我在使用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);
}
}
}
没有找到相关结果
已邀请:
3 个回复
钨蜡唤喉晤
臀博
由服务控制器启动服务时运行,因为服务控制器未将任何参数传递给Main()。 如果不执行ѭ5,则您的服务将不会响应来自服务控制器的任何命令,并且会看到错误。
容淑阔九