【问题标题】:Why the timer tick event keep calling the method twice in a row and not after 10 seconds each time?为什么计时器滴答事件连续两次调用该方法,而不是每次 10 秒后?
【发布时间】:2014-07-15 13:18:20
【问题描述】:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Timers;

namespace ScrollLabelTest
{

    class SaveOldHtml
    {
        private static int count;
        private static Timer _timer = new Timer();
        private static string page;
        private static List<string> newText = new List<string>();

        public SaveOldHtml(string DirectoryToSave,int count, string contents)
        {
            System.IO.File.WriteAllText(DirectoryToSave + "Page" + count.ToString("D6")
                                        + ".html", contents);
        }

        public SaveOldHtml(string DirectoryToSave, List<string> newTextList, int count)
        {
            using (StreamWriter myStream = new StreamWriter(DirectoryToSave + "newTextList" + count.ToString("D6")
                                        + ".txt"))
            {
                for (int i = 0; i < newTextList.Count; i++)
                {
                    myStream.WriteLine(newTextList[i]);
                }

            }
        }

        public static void Start()
        {
            _timer.Elapsed += _timer_Elapsed;
            _timer.Interval = 10000;
            count = 5;
            LoadOldHtmlFiles();
            _timer.Start();
        }

        static void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            LoadOldHtmlFiles();
        }

        private static void LoadOldHtmlFiles()
        {

            page = File.ReadAllText(@"c:\temp\OldHtml\page" + count.ToString("D6") + ".html");
            ListsExtractions.OffExtractions(@"c:\temp\OldHtml\page" + count.ToString("D6") + ".html", page, newText);
            count ++;
        }
    }
}

问题是我第一次在 Start 方法中调用 LoadoldHtmlfiles 一次,然后在 10 秒后我在计时器滴答事件中再次调用它。 但是下次它不会再等待 10 秒,而是立即跳转到计时器滴答事件并再次调用 LoadoldhmtlFiles。

我检查了几次并搜索了我在 form1 构造函数中调用方法 Start onlny 的所有解决方案。

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:

    如果LoadOldHtmlFiles() 花费 >= 10 秒,那么您的计时器将重复触发它。停止计时器并在_timer_Elapsed 方法中重新启动它:

    static void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        _timer.Stop();
        LoadOldHtmlFiles();
        _timer.Start();
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      • 2016-01-29
      • 2019-06-13
      相关资源
      最近更新 更多