为什么计时器刻度事件连续两次调用方法而不是每次10秒后?

时间:2014-07-15 13:18:20

标签: c# .net winforms

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秒后我再次在timer tick事件中调用它。 但是接下来它没有等待另外10秒,而是立即跳到计时器滴答事件并再次调用LoadoldhmtlFiles。

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

1 个答案:

答案 0 :(得分:6)

如果LoadOldHtmlFiles()需要&gt; = 10秒,那么您的计时器将重复触发它。停止计时器并使用_timer_Elapsed方法重新启动它:

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