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 一次的所有解决方案。
最佳答案
如果 LoadOldHtmlFiles()
花费 >= 10 秒,那么您的计时器将重复触发它。停止计时器并在 _timer_Elapsed
方法中重新启动它:
static void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
_timer.Stop();
LoadOldHtmlFiles();
_timer.Start();
}
关于c# - 为什么计时器滴答事件连续调用该方法两次而不是每次10秒后调用该方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24759281/