more Docs 就是 more Documents 既 更多文档,更多资料! - 本站致力于提供更多精彩的免费资料、文档、图片,宁缺不烂,一起分享网络、分享快乐!
设置首页 - 加入收藏

如何用c# 开发系统服务

2008-9-3 19:00:43 来源:本站 浏览: 评论:

最近用.net开发了个隔时执行的小应用程序,登录MSDTC,放到服务器,运转良好,退出远程桌面,事情出来了,那个可爱的程序不运作了,然后我就搞了个任务计划,做了下,以为完事了,过了一些时间,发现不对劲,还是停止执行程序了,上去一看,又停止了,这时候我不得不重新考虑设置,还是写个系统服务就去吧,写上一段代码先写个服务再说。

 程序代码

using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;
using System.Configuration.Install;

namespace CjjerTest.DotNet.ServiceDST
{
    // 应用程序
    public class MyFirstService : System.ServiceProcess.ServiceBase
    {
        public MyFirstService()
        {
            this.CanPauseAndContinue = true;
            this.CanShutdown = true;
            this.CanHandleSessionChangeEvent = false;

            this.ServiceName = "MyFirstService";
        }

        protected override void OnStart(string[] args){

        }
        protected override void OnStop(){

        }
        protected override void OnContinue(){

        }
        //启动
        public static void Main()
        {
            ServiceBase[] servicesToRun = new ServiceBase[] {new MyFirstService()};
            ServiceBase.Run(servicesToRun);
        }
    }

    //安装
    [RunInstaller(true)]
    public class ProjectInstaller : System.Configuration.Install.Installer
    {
        private ServiceProcessInstaller myServiceProcessInstaller;
        private ServiceInstaller myServiceInstaller;

        public ProjectInstaller()
        {
            this.myServiceProcessInstaller = new ServiceProcessInstaller();
            this.myServiceInstaller = new ServiceInstaller();

            // 安装
            // 用户名 和 密码
            this.myServiceProcessInstaller.Account = ServiceAccount.LocalSystem;
            this.myServiceProcessInstaller.Username = null;
            this.myServiceProcessInstaller.Password = null;

            // 服务名称,这样可以在net stop XX 里面使用了
            // 启动类型
            this.myServiceInstaller.ServiceName = "MyFirstService";
            this.myServiceInstaller.StartType = ServiceStartMode.Automatic;

            // 加入
            this.Installers.AddRange(new Installer[] {this.myServiceProcessInstaller, this.myServiceInstaller});
        }
    }
}


其中在启动的代码中我们可以执行:

 程序代码

        protected override void OnStart(string[] args){   
            StreamWriter sw=new StreamWriter(@"E:\web\web\net\test\sernet.txt",true);
            sw.Write("\r\n另一条数据");
            sw.Close();

            base.OnStart( args );
        }

   
或者创建另一条线程执行其他程序。

1、编译
   
csc cservice.cs
   
2、安装
   
installutil cservice.exe
   
3、启动服务
   
net start MyFirstService
   
4、停止服务
   
net stop MyFirstService
   
5、卸载
   
installutil /u cservice.exe


[1] [2] 
分享网络,分享快乐,我为人人,人人为我,转载请注明转自 moreDocs.com 谢谢!
栏目推荐
全站推荐
栏目热门
全站热门
免责声明:本站文章全部来自网络,版权归作者所有,这里只供学习参考之用,请勿抄袭和做其他用途.如侵犯了您的版权,请来信说明,本站立即删除!