首页 > 技术文章 > Windows Service的转换与部署

yisss 2013-12-24 17:37 原文

开发Windows Service,可能会碰到以下两种情况。

1. 直接开发一个Windows Service

网上有很多教程,可以参考这个:

http://www.cnblogs.com/sorex/archive/2012/05/16/2502001.html


 

有可能遇到的问题:

  http://www.csharpwin.com/csharpspace/6705r3252.shtml

  http://tieba.baidu.com/p/764186736

 

2. 假设已有一个写好的project,现把它转换为windows service

 1)改写Main

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            //如果是双击打开
            if (Environment.UserInteractive)
            {
                OnStart(args);
            }    
            //如果是以windows service形式运行
            else
            {
                using (var service = new LogService(OnStart, OnStop))
                {
                    ServiceBase.Run(service);
                }
            }
        }
        //添加Windows service需要的OnStart和OnStop方法
        internal static void OnStart(string[] args)
        {
            //Project中本来在Main中的code
            while (true)
            {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter("log.txt", true))
                {
                    sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start.");
                }
                Thread.Sleep(3000);
            }
        }
        internal static void OnStop()
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter("log.txt", true))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Stop.");
            }
        }
    }
}    

2)添加service类,继承ServiceBase,实现以windows service启动的情况。注意service类的type为Window Service类,且需要引用System.ServiceProcess.dll

  右键点击Service类,选择view code,添加代码如下:

namespace Test
{
    partial class LogService : ServiceBase
    {
        private Action<string[]> _onStart;
        private Action _onStop;
        public LogService(Action<string[]> onStart, Action onStop)
        {
            ServiceName = "LogService";

            _onStart = onStart;
            _onStop = onStop;
        }
        public LogService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.
            if (_onStart != null)
                _onStart(args);
        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            if (_onStop != null)
                _onStop();
        }
    }
}

3)写安装和删除脚本

sc create LogService binPath= C:\Users\sunyi\Desktop\test2\Test.exe
  sc start LogService
  pause


    net stop LogService
  sc delete LogService
  pause

4)在windows服务管理中即可查看到启动的windows service

 

 

 

 

推荐阅读