C# 开发windows服务

 windows下无法像linux那样直接运行nohup等命令运行后台程序,只能调用相应api做成服务。服务可以在没有任何用户登录计算机的情况下运行。C# 建立windows 服务比较方便,直接派生 System.ServiceProcess.ServiceBase,但是只支持windows XP。

  

/// <summary>
/// 1.建立windows服务类,派生于ServoceBase
/// <summary>
partial class MainService : ServiceBase
{
	/** 
	 * 服务启动时调用,此时代码要立即返回。否则服务启动时一直等待,
	 * 造成服务启动失败。最好启动线程或定时器。
	 *
	 */
	protected override void OnStart(string[] args)
	{
	    File.WriteAllText(@"d:\log.log","Start service");
	}

	// 服务停止时调用
	protected override void OnStop()
	{
	    File.WriteAllText(@"d:\log.log","Stop service");
	}
}


/// <summary>
/// 2.启动服务
/// </summary>
static void Main(string[] args)
{
	// 服务列表
    ServiceBase[] ServiceToRun = new ServiceBase[]
    {
        new MainService(),
    };

    ServiceBase.Run(ServiceToRun);		// 可以同时启动多个服务
}


/// <summary>
/// 3.安装服务,设置RunInstallerAttribute 
/// </summary>
[RunInstallerAttribute(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
    public ProjectInstaller()
    {
        InitializeComponent();
    }

    private void serviceProcessInstaller1_AfterInstall(object sender, InstallEventArgs e)
    {

    }
}
 

上述方式,需要运行 InstallUtil.exe /i 程序.exe 安装服务

 卸载服务: InstallUtil.exe /u 程序.exe,服务管理不太方便,可通过直接调用sc命令实现自动管理服务。

/// 命令行自动安装卸载服务
static void Main(string[] args)
{
    // 自动安装卸载服务
    if (args.Length > 0 && args[0] == "d")
    {
        ServiceBase[] ServiceToRun = new ServiceBase[]
        {
            new MainService(),
        };

        ServiceBase.Run(ServiceToRun);
    }
    else
    {
        Console.WriteLine("Usage:[1]install [2]uninstall [3]exit");
        var rs = int.Parse(Console.ReadLine());

        switch(rs)
        {
            case 1:
                var path = Process.GetCurrentProcess().MainModule.FileName + " d";
                Process.Start("sc", "create whitesynserver binpath= \"" + path + "\" displayName= 白名单同步服务 start= auto");
                Console.WriteLine("安装成功");
                Console.Read();
                break;
            case 2:
                Process.Start("sc", "delete whitesynserver");
                Console.WriteLine("卸载成功");
                Console.Read();
                break;
            case 3:
                break;
            default:
                break;
        }
    }
}

猜你喜欢

转载自tcspecial.iteye.com/blog/2280875