现在的位置: 首页 > 综合 > 正文

如何在asp.net中编写 Windows 服务程序 Visual Studio编写 Windows 服务

2012年08月11日 ⁄ 综合 ⁄ 共 1114字 ⁄ 字号 评论关闭

1、新建 >> 项目 >> Visual C# >> Windows >> Windows服务;
2、一般服务程序中我们都需要使用到 Timer 组件,建议不要使用 System.Windows.Forms.Timer 组件,因为它可能会产生不可预料的“罢工”问题;应使用 System.Timer 组件;可以在  Service 的 OnStart 过程中编写如下:
protected override void OnStart(string[] args)
{
    Timer timer = new Timer(1000);
    timer.Elapsed += new ElapsedEventHandler(DoAnything); //使用Elapsed事件,其中DoAnything就是你需要处理的事情
    timer.AutoReset = true;
    timer.Enabled = true;
}

private void DoAnything(object sender, System.Timers.ElapsedEventArgs e)
{
    .... 你需要做的事情写这里
}

3、写完之后,最终是需要将它安装到 Windows 服务中,因此需要在现有工程中 添加 >> 新建项 >> 安装程序类,取名叫:ProjectInstaller.cs;在类中还需要两个控件支持,分别是:serviceInstaller 与 serviceProcessInstaller,这两个组件在 .net 2.0 包中已经包含,只是默认不显示在工具箱中,可以从工具箱中增加“选择项”,将它们找出来。其中serviceInstaller可以设置服务的显示名称、说明、运行方式(建议设置成自动:Automatic)等信息;serviceProcessInstaller用于设置服务运行的账户身份,推荐设置成:LocalSystem(本地账户);

一切就绪后,Ctrl + Alt +B 编译程序,服务程序基本上就到此完成!此时服务程序只是编译好了,并未最终安装到WINDOWS 服务中,还需要写一段批处理用于注册该服务程序,以下提供批处理文件代码。

installService.bat(注册与启动)
==================
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe 服务程序绝对路径
net start 服务名

unInstallService.bat(卸载与停止)
==================
net stop 服务名
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe -u 服务程序绝对路径

抱歉!评论已关闭.