Chinaunix首页 | 论坛 | 博客
  • 博客访问: 24728
  • 博文数量: 11
  • 博客积分: 445
  • 博客等级: 下士
  • 技术积分: 240
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-14 14:27
文章分类
文章存档

2012年(11)

我的朋友
最近访客

分类: 嵌入式

2012-05-31 09:04:05

创建Windows服务(Windows Services)N种方式总结
最近由于工作需要,写了一些windows服务程序,有一些经验,我现在总结写出来。
 目前我知道的创建创建Windows服务有3种方式:
 a.利用.net框架类ServiceBase
 b.利用组件Topshelf。更多文章http://wialoigie.blog.51cto.com
 c.利用小工具instsrv和srvany
 
下面我利用这3种方式,分别做一个windows服务程序,程序功能就是每隔5秒往程序目录下记录日志:
 
 
 
a.利用.net框架类ServiceBase
 
本方式特点:简单,兼容性好
 
通过继承.net框架类ServiceBase实现
 
第1步: 新建一个Windows服务
 
 
     public partial class Service1 : ServiceBase
    {
        readonly Timer _timer;
        private static readonly string FileName = Path.GetDirectoryName ( Assembly.GetExecutingAssembly ( ).Location ) + @"\" + "test.txt";
        public Service1 ( )
        {
            InitializeComponent ( );
            _timer = new Timer ( 5000 )
            {
                AutoReset = true ,
                Enabled = true
            };
            _timer.Elapsed += delegate ( object sender , ElapsedEventArgs e )
            {
                this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );
            };
        }
        protected override void OnStart ( string [ ] args )
        {
            this.witre ( string.Format ( "Start DateTime {0}" , DateTime.Now ) );
        }
        protected override void OnStop ( )
        {
            this.witre ( string.Format ( "Stop DateTime {0}" , DateTime.Now ) + Environment.NewLine );
        }
        void witre ( string context )
        {
            StreamWriter sw = File.AppendText ( FileName );
            sw.WriteLine ( context );
            sw.Flush ( );
            sw.Close ( );
        }
    } 
 
健康知识
阅读(992) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~