• Windows Service异常,都是偷懒惹的祸


    使用Timer  

      平时在开发过程中,有时候图省事,直接拖入Window控件包里的Timer控件去为我们这事情,但是今天在写程序的时候出现异常,费了一番功夫找到问题原因,以此记录一下。

      将timer控件拖到WindowService设计中,双击timer生成事件,在Designer.cs中自动生成如下代码:

            private System.Windows.Forms.Timer timer1;
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.timer1.Interval = 10000;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);

      然后我在timer1_click事件中,编写代码,期望它能按时执行。事实上,在部署WindowService程序时发现它并没起到作用。WindowService调试方法,是在服务运行时或运行后,使用VS调试中的附加进程。但在调试过程中,发现事件并未执行,通过查找msdn,发现WindowService程序中,timer控件不是这样用的。正确的timer定义与使用如下:

            private System.Timers.Timer timer1;
            this.timer1 = new System.Timers.Timer();
            this.timer1.Enabled = true;
            this.timer1.Interval = 7200D;
            this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);

      这样看起来会发现,它的声明与事件都是不相同的,代码很简单。按照以上代码,修改即可。

    使用.代表根目录

      在上述timer的elapsed事件里,我写的代码是

                //检查日志文件删除
                if (Directory.Exists("./Logs"))
                {
                    var files = Directory.GetFiles("./Logs");
                    //设置保存近3天的日志文件
                    var oldDate = DateTime.Now.AddDays(-3);
                    foreach (var file in files)
                    {
                        var updateTime = File.GetLastWriteTime(file);
                        if (updateTime < oldDate)
                        {
                            File.Delete(file);
                        }
                    }
                }

      在目录的判断中发现该判断返回false,于是意识到可能是偷懒写.引起的,后来更换成 AppDomain.CurrentDomain.SetupInformation.ApplicationBase ,问题解决了。用.代表根目录,在Winform程序中是可以的,但是在WindowService程序中.指向了system32。

  • 相关阅读:
    Java 入门25 继承 this super
    Java 18 String 常用API
    Java 入门21 java 进阶大纲 及复习
    Java 入门20 ArrayList 小案例实践
    面试集合
    面试~设计模式单例模式
    系统入门到实战学习某项技术、有问题找"百度"、学习大佬的技术博客、找开源代码等资料
    面试~双亲委派模型
    面试面向对象7大设计原则
    第一二章学习心得
  • 原文地址:https://www.cnblogs.com/codealone/p/3115226.html
Copyright © 2020-2023  润新知