Windows Service

     用Visual Studio创建一个Windows Service非常简便。新建项目,然后选择Windows服务。
     用在一个服务里使用脉冲时间不能用System.Windows.Forms.Timer控件,要使用System.Timers.Timer。
     在Service类里面定义一个私用成员。
     System.Timers.Timer timer = new System.Timers.Timer();     
     然后在OnStart事件里进行设置:
      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
      timer.Interval = 5000;
      timer.Start();
      首先给Elapsed事件添加委托。这是个脉冲事件,隔Interval 时间就触发一次。下面是timer_Elapsed函数的定义。
       protected void timer_Elapsed(object sender, ElapsedEventArgs e)
        {   
            File.AppendAllText("C:/WindowsService.txt", DateTime.Now.ToString() + ";");
        }
     里面用来放业务逻辑。
     然后调用Start方法,这个步骤是不能少的。
     最后在Service类的OnStop方法中调用Timer的Stop方法。

     接下来进行安装。首先在Service界面点击右键,选择“添加安装程序”。然后在生成菜单中生成该项目。
     接着使用.net的InstallUtil.exe安装服务。
     在“运行”里键入cmd,进入windows命令行,首先进入InstallUtil.exe的安装目录
     cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
     然后使用 installutil  E:\asp.net3.5\IntegrationTest.exe安装自己的项目。
     如果对项目进行了改动,则必须使用installutil -u E:\asp.net3.5\IntegrationTest.exe先进服务卸载,再重新安装。

     调试服务的方法是在项目的Program.cs文件的Main方法中加入下列程序。    

#if DEBUG
            System.Diagnostics.Debugger.Launch();
#endif
     这样在服务启动的时候,会弹出对话框选择调试程序。

posted on 2009-02-23 22:10  林骄  阅读(407)  评论(0)    收藏  举报