在命令行中运行Windows服务

在命令行中运行Windows服务

本文介绍了在命令行中运行Windows服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能开发一个可以作为普通服务运行的Windows服务,但也可以在命令行中使用参数启动?



c:\ myservice.exe -i(=>这将调用InstallUtil.exe并安装我的服务)

c:\ myservice.exe -u(=>这将调用InstallUtil.exe -u并卸载我的服务)

c:\ myservice.exe -debug(=>这会给我额外的日志用于调试目的)

Is there any possiblity to develop a windows service that will run as normal service, but also can start in commandline with parameters ?

c:\myservice.exe -i ( => this will call InstallUtil.exe and install my service )
c:\myservice.exe -u ( => this will call InstallUtil.exe -u and uninstall my service )
c:\myservice.exe -debug( => this will give me extra logging for debug purposes )

推荐答案

public class MyService : ServiceBase
{
    private void StartService()
    {
        // initialization code
    }
    protected override void OnStart(string[] args)
    {
        base.OnStart(args);
        StartService();
    }
    private void StopService()
    {
        // shutdown code
    }
    protected override void OnStop()
    {
        base.OnStop();
        StopService();
    }
    public static void Main(string[] args)
    {
        bool runStandAlone = false;
        // parse command line arguments to populate runStandAlone 

        var service = new MyService();
        if (runStandAlone)
        {
            service.StartService();
            Console.WriteLine("Service is running in standalone mode.\r\nPress any key to stop...");
            Console.ReadKey();
            service.StopService();
        }
        else
            Run(service);
    }
}



要安装和卸载服务,您需要创建 [] class然后使用 []将调用安装程序。


To install and uninstall the service you need to create an Installer[^] class and then use installutil.exe[^] which will invoke the installer.


这篇关于在命令行中运行Windows服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 01:10