在C#中启动Windows服务

2 c# windows-services

我想启动刚刚安装的Windows服务.

ServiceBase[] ServicesToRun;
if (bool.Parse(System.Configuration.ConfigurationManager.AppSettings["RunService"]))
{
    ServicesToRun = new ServiceBase[] { new IvrService() };
    ServiceBase.Run(ServicesToRun);
}
Run Code Online (Sandbox Code Playgroud)

IvrService代码是:

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;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我不知道如何启动该服务.使用ServiceController.Start()?但我已经有了ServiceBase.Run(ServicesToRun);它是否可以启动服务?

代码提示绝对值得赞赏.

jos*_*ley 5

要回答有关从代码启动服务的问题,您可能需要这样的东西(这相当于net start myservice从命令行运行):

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.");
    }
}
Run Code Online (Sandbox Code Playgroud)

这将启动服务,但请记住,它将与执行上述代码的进程不同.


现在回答有关调试服务的问题.

  • 一种选择是在服务启动附加.
  • 另一种方法是使您的服务可执行文件能够运行主代码,而不是作为服务而是作为普通可执行文件(通常通过命令行参数设置).然后你可以从你的IDE进入F5.


编辑:添加事件的样本流(基于一些评论的问题)

  1. 要求操作系统启动服务.这可以通过控制面板,命令行,API(如上面的代码)或OS自动完成(取决于服务的启动设置).
  2. 然后,操作系统创建一个新进程.
  3. 然后,该进程注册服务回调(例如,ServiceBase.Run在C#中或StartServiceCtrlDispatcher在本机代码中).然后开始运行其代码(将调用您的ServiceBase.OnStart()方法).
  4. 然后OS可以请求暂停,停止等服务.此时它将向已经运行的进程发送控制事件(从步骤2开始).这将导致调用您的ServiceBase.OnStop()方法.


编辑:允许服务作为普通可执行文件或命令行应用程序运行:一种方法是将您的应用程序配置为控制台应用程序,然后根据命令行开关运行不同的代码:

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
    }
Run Code Online (Sandbox Code Playgroud)