在 C# 中启动 Windows 服务 [英] Start Windows Service in C#
问题描述
我想启动一个刚刚安装的 windows 服务.
I want to start a windows service that was just installed.
ServiceBase[] ServicesToRun;
if (bool.Parse(System.Configuration.ConfigurationManager.AppSettings["RunService"]))
{
ServicesToRun = new ServiceBase[] { new IvrService() };
ServiceBase.Run(ServicesToRun);
}
IvrService 代码是:
The IvrService code is:
partial class IvrService : ServiceBase
{
public IvrService()
{
InitializeComponent();
Process myProcess;
myProcess = System.Diagnostics.Process.GetCurrentProcess();
string pathname = Path.GetDirectoryName(myProcess.MainModule.FileName);
//eventLog1.WriteEntry(pathname);
Directory.SetCurrentDirectory(pathname);
}
protected override void OnStart(string[] args)
{
string sProcessName = Process.GetCurrentProcess().ProcessName;
if (Environment.UserInteractive)
{
if (sProcessName.ToLower() != "services.exe")
{
// In an interactive session.
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new IvrInteractive());
IvrApplication.Start(); // the key function of the service, start it here
return;
}
}
}
我不确定如何启动该服务.使用 ServiceController.Start()?
但是我已经有了 ServiceBase.Run(ServicesToRun);
是用来启动服务的吗?
I am not sure how to start the service. Using ServiceController.Start()?
But I already have ServiceBase.Run(ServicesToRun);
Is it for starting a service?
代码提示绝对值得赞赏.
Code hint is definitely appreciated.
推荐答案
要回答有关从代码启动服务的问题,您可能需要这样的东西(相当于运行 net start myservice
从命令行):
To answer the question about starting a service from code, you would want something like this (which would be equivalent to running net start myservice
from the command line):
ServiceController sc = new ServiceController();
sc.ServiceName = "myservice";
if (sc.Status == ServiceControllerStatus.Running ||
sc.Status == ServiceControllerStatus.StartPending)
{
Console.WriteLine("Service is already running");
}
else
{
try
{
Console.Write("Start pending... ");
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 10));
if (sc.Status == ServiceControllerStatus.Running)
{
Console.WriteLine("Service started successfully.");
}
else
{
Console.WriteLine("Service not started.");
Console.WriteLine(" Current State: {0}", sc.Status.ToString("f"));
}
}
catch (InvalidOperationException)
{
Console.WriteLine("Could not start the service.");
}
}
这将启动服务,但请记住,它与执行上述代码的进程不同.
This will start the service, but keep in mind that it will be a different process than the one that is executing the above code.
现在回答调试服务的问题.
Now to answer the question about debugging a service.
- 一种选择是在服务启动后附加.
- 另一个是使您的服务可执行文件能够运行主代码,而不是作为服务而是作为普通可执行文件(通常通过命令行参数设置).然后你可以从你的 IDE 中按 F5 进入它.
添加示例事件流(基于一些评论中的问题)
Adding sample flow of events (based on questions from some of the comments)
- 要求操作系统启动服务.这可以通过控制面板、命令行、API(如上面的代码)或由操作系统自动完成(取决于服务的启动设置).
- 然后操作系统会创建一个新进程.
- 然后该进程注册服务回调(例如,C# 中的
ServiceBase.Run
或本机代码中的StartServiceCtrlDispatcher
).然后开始运行它的代码(它将调用您的ServiceBase.OnStart()
方法). - 然后操作系统可以请求暂停、停止服务等.此时它会向已经运行的进程发送一个控制事件(从第 2 步开始).这将导致调用您的
ServiceBase.OnStop()
方法.
- OS is asked to start a service. This can be done from the control panel, the command line, APIs (such as the code above), or automatically by the OS (depending on the service's startup settings).
- The operating system then creates a new process.
- The process then registers the service callbacks (for example
ServiceBase.Run
in C# orStartServiceCtrlDispatcher
in native code). And then starts running its code (which will call yourServiceBase.OnStart()
method). - The OS can then request that a service be paused, stopped, etc. At which point it will send a control event to the already running process (from step 2). Which will result in a call to your
ServiceBase.OnStop()
method.
允许服务作为普通可执行文件或命令行应用程序运行:一种方法是将您的应用程序配置为控制台应用程序,然后根据命令行开关运行不同的代码:
Allowing a service to run as a normal executable or as a command line app: One approach is to configure your app as a console application, then run different code based on a command line switch:
static void Main(string[] args)
{
if (args.Length == 0)
{
// we are running as a service
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyService() };
ServiceBase.Run(ServicesToRun);
}
else if (args[0].Equals("/debug", StringComparison.OrdinalIgnoreCase))
{
// run the code inline without it being a service
MyService debug = new MyService();
// use the debug object here
}
这篇关于在 C# 中启动 Windows 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!