window service 开发

为了便于window service的调试和开发。

我整理了一下代码,方便大家查阅


App.config

设置启动时间

timerStart-10点

interval-3600000  1小时检查一次

isdebug-调试模式

<!--timer-->
    <add key="timerStart" value="10" />
    <add key="interval" value="3600000" />
<!--IsDebug-->
    <add key="IsDebug" value="true" />
<!--Log-->
    <add key="logPath" value="D:\Log\" />



Program

static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        static void Main()
        {
            
            if (MyConfig.IsDebug)
            {
                //测试
                Service1 s = new Service1();
            }
            else
            {
                //正式
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                new Service1()
                };
                ServiceBase.Run(ServicesToRun);
            }
        }
    }


Service

public Service1()
        {
            InitializeComponent();
//全局异常
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            //运行
            RunService();
        }

        System.Timers.Timer timer1 = new System.Timers.Timer(MyConfig.interval);
       
        protected override void OnStart(string[] args)
        {
            //正式
            if (!MyConfig.IsDebug)
            {
                timer1.AutoReset = true;
                timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
                timer1.Enabled = true;
            }
        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (DateTime.Now.Hour == MyConfig.timerStart)
            {
                RunService();
            }
        }

        public void RunService()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            LogHelper.WriteLog("  <<==开始______________________" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "______________________==>>");

            try
            {
                //处理逻辑
                DoSomeThing();

                LogHelper.WriteLog("  <<==结束______________________" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "______________________==>>");
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message);
                LogHelper.WriteLog(ex.StackTrace);
                LogHelper.WriteLog("  <<==结束______________________" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "______________________==>>");
            }
            finally
            {
                Clear();
            }

            
        }

        protected override void OnStop()
        {
            //正式
            timer1.Enabled = false;
        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                Exception ex = e.ExceptionObject as Exception;
                string exStr = "\n" + "\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ex.Message + "详细信息如下:\n"
                                    + Environment.NewLine + "[InnerException]" + ex.InnerException + "\n"
                                    + Environment.NewLine + "[Source]" + ex.Source + "\n"
                                    + Environment.NewLine + "[TargetSite]" + ex.TargetSite + "\n"
                                    + Environment.NewLine + "[StackTrace]" + ex.StackTrace + "\n";
                LogHelper.WriteLog(exStr);

            }
            catch { }
            finally { }
        }




LogHelper

public class LogHelper
    {
        public static readonly string logPath = ConfigurationManager.AppSettings["logPath"];
        private static readonly object writeFile = new object();
        public LogHelper() { }

        /// <summary>
        /// 在本地写入错误日志
        /// </summary>
        /// <param name="exception"></param> 
        public static void WriteLog(string debugstr)
        {
            lock (writeFile)
            {
                FileStream fs = null;
                StreamWriter sw = null;

                try
                {
                    string filename = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                    //服务器中日志目录

                    if (!Directory.Exists(logPath))
                        Directory.CreateDirectory(logPath);
                    fs = new FileStream(logPath + "/" + filename, System.IO.FileMode.Append, System.IO.FileAccess.Write);
                    sw = new StreamWriter(fs, Encoding.UTF8);
                    sw.WriteLine(DateTime.Now.ToString() + "     " + debugstr + "\r\n");
                }
                finally
                {
                    if (sw != null)
                    {
                        sw.Flush();
                        sw.Dispose();
                        sw = null;
                    }
                    if (fs != null)
                    {
                        //     fs.Flush();
                        fs.Dispose();
                        fs = null;
                    }
                }
            }
        }

    }




posted @ 2017-10-19 11:46  正怒月神  阅读(135)  评论(0编辑  收藏  举报