双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

定时器的调用函数作用域内的变量定义是否存在延迟?

sosowen1 sosowen1 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
这个是楼主写的一个定时监测程序的代码片段,其中active为一个全局变量,按照程序的判断逻辑,是不可能存在连续两个"start!!!!!"的,但是在实际运行时,试过出现连续6个"start!!!!!!"
        System.Timers.Timer aTimer = new System.Timers.Timer();
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(AtTimeEvent);
fsPermance = new FileStream("e:\\permance" + DateTime.Now.ToString("MMddhhmm") + ".txt", FileMode.Create);
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 1000;
aTimer.Enabled = true;

      if (value > 8 && !active && memory > 40 && !dc.Responding)
{

Console.WriteLine(active.ToString());
active = true;
start = new TimeSpan(DateTime.Now.Ticks);
Console.WriteLine("start!!!!!!!"+DateTime.Now.ToShortTimeString());
}
else if (value < 5 && active && dc.Responding)
{
active = false;
TimeSpan end = new TimeSpan(DateTime.Now.Ticks);
resultLog( end - start);
Console.WriteLine("end!!!!!!!!!"+DateTime.Now.ToShortTimeString());
}


之后我自己又写了一个测试代码
string t = Console.ReadLine();
int value = int.Parse(t);
if (!active && value > 10)
{
Console.WriteLine("start");
active = true;
}
else if (active && value < 10)
{
Console.WriteLine("end");
active = false;
}

这个即使我不断输入,最后的逻辑也是对的。所以我现在感到非常困惑,下面那个没问题,为什么上面那个会出现这种情况呢?
楼主是新学C#的,对于里面的一些机制也不是非常理解,希望各位前辈能不吝指正
...全文

相关推荐

评论 9
收藏 已收藏
分享
返回顶部
sosowen1
C# 111,129 成员 642,540 内容