zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    《HTTP权威指南》之HTTP连接管理及对TCP性能的考虑
    TCP/ip
    java scoket http TCP udp
    java ==和equals区别
    Java 流
    android ViewPager,ViewFlipper,ViewFlow实现左右滑动
    java反射详解
    退出清理所有Activity方法
    Android UI 使用Merge,include和 ViewStub--优化(1)
    android resources使用总结
  • 原文地址:https://www.cnblogs.com/codealone/p/3115226.html
Copyright © 2011-2022 走看看