【转】如何编写C# Windows服务

1、新建C# Windows服务:windows service工程

2、新建windows service工程后,系统自动生成一个Service1.cs文件,默认是其设计视图。选择查看其代码,默认有构造函数、OnStart、OnStop三个函数,如下图所示:

3、新建了C# Windows服务之后,还要设置该服务运行的周期,左侧的ToolBox中有两个timer,一个在组件下,一个在windows form下,可惜这两个都不能用,我们要手工新建一个timer,并设置其属性和事件。

public WindowsServiceDemo()           {  
            InitializeComponent();              
            System.Timers.Timer t = new System.Timers.Timer(1000);//实例化Timer类,设置间隔时间为10000毫秒;                
            t.Elapsed += new System.Timers.ElapsedEventHandler(TimeElapse);//到达时间的时候执行事件;                
            t.AutoReset = true;//设置是执行一次(false)还是一直执行(true);                
            t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;           
        }     

        public void TimeElapse(object source, System.Timers.ElapsedEventArgs e)           
        {               
            //EventLog log = new EventLog("System");               
            //log.Source = "My Application";               
            //log.WriteEntry("1秒调用一次", EventLogEntryType.Information);               
            FileStream fs = new FileStream(@"d:\timetick.txt", FileMode.OpenOrCreate, FileAccess.Write);               
            StreamWriter m_streamWriter = new StreamWriter(fs);               
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);               
            m_streamWriter.WriteLine("过了一秒 " + DateTime.Now.ToString() + "\n");               
            m_streamWriter.Flush();              
            m_streamWriter.Close();               
            fs.Close();               
        }  

4、服务编写之后,还不能由SCM(服务控制管理器)进行管理,需要给该服务添加装载器。在Service1.cs的设计视图,点击右键,选择“添加装载器”,系统默认就会添加ProjectInstaller.cs这个类。

5、添加该类后,在该类的设计视图上可看到serviceInstaller1和serviceProcessInstaller1,分别设置其属性。

设置serviceInstaller1的运行方式为手动或者自动

设置serviceInstaller1的ServiceName,设置为什么,服务列表中就显示什么

设置serviceProcessInstaller1的运行账号为LocalSystem

6、编译该工程

7、使用vs自带的命令行工具,运行installutil 编译生成的exe

8、在系统的服务中可看到我们创建的服务。

需要注意的是:

如果你修改了这个服务,路径没有变化的话是不需要重新注册服务的,如果路径发生了变化,需要先卸载这个服务InstallUtil.exe /u参数,然后再重新安装这个服务,不能直接安装。还有就是C# Windows服务是没有界面的,不要企图用控制的输出方式来输出一些信息,你只能添加一个EventLog,通过WriteEntry()来写日志。

9、创建安装脚本

在项目中添加2个文件如下(必须是ANSI或者UTF-8无BOM格式):

1)安装脚本Install.bat

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe WindowsServiceTest.exe
Net Start ServiceTest
sc config ServiceTest start= auto

2)卸载脚本Uninstall.bat

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u WindowsServiceTest.exe

3)安装脚本说明

第二行为启动服务。

第三行为设置服务为自动运行。

这2行视服务形式自行选择。

4)脚本调试

如果需要查看脚本运行状况,在脚本最后一行加入pause

转自:http://www.csharpwin.com/csharpspace/5575r154.shtml

        http://www.cr173.com/html/15350_1.html

关于EventLog 参考:http://www.cnblogs.com/nokiaguy/archive/2009/02/26/1398708.html

如果要在服务中弹窗,如: Process.Start("notepad.exe");

设置:服务 选择“属性”——》 单击“登录”标签(在最上面)——》选择本地系统帐户——》在“允许服务与桌面交互”复选框前打勾

posted @ 2013-10-10 15:59  伯箫  阅读(248)  评论(0)    收藏  举报