如何在类中正确使用 System.Timers.Timer
我正在尝试学习如何使用计时器,但我在处理已过去的事件时遇到了麻烦。 我所拥有的是一个类,我可以在其中检查来自数据批的一些消息。但现在我想制作一个计时器,每隔 x 时间段检查该消息。
我编写了这段代码:
public class Program
{
static void Main(string[] args)
{
Message m = new Message();
m.init();
}
}
public class Messages{
private System.Timers.Timer tt;
public void init()
{
tt = new(_conf.Period);
tt.Elapsed += new System.Timers.ElapsedEventHandler(TimerElapsed);
tt.Start();
Console.ReadLine();
}
private void TimerElapsed(object? sender, ElapsedEventArgs e)
{
//Console.WriteLine for test it works
Console.WriteLine(DateTime.UtcNow);
//check my messages
}
}
这不起作用,因为它永远不会进入 TimerElapsed 内部。我做错了什么?
谢谢
编辑:即使现场计时器不会进入已发生的事件。
EDIT2:好吧,我发现了我的问题。我正在使用 Console.WriteLine(DateTime.UtcNow) 内部测试 TimerElapsed,只有当我将所有代码放在 Init 上的 Console.ReadLine(); 上时,它才有效。我将再次编辑我的代码来显示它。我不明白为什么我需要这个 readLine,所以如果有人可以向我解释那就太好了。
I'm trying to learn how to use Timers and I'm having troubles with the elapsed event.
What I have is a class where I check some messages from a databatch. But now I want to make a timer where every x period of time check that messages.
I made this code:
public class Program
{
static void Main(string[] args)
{
Message m = new Message();
m.init();
}
}
public class Messages{
private System.Timers.Timer tt;
public void init()
{
tt = new(_conf.Period);
tt.Elapsed += new System.Timers.ElapsedEventHandler(TimerElapsed);
tt.Start();
Console.ReadLine();
}
private void TimerElapsed(object? sender, ElapsedEventArgs e)
{
//Console.WriteLine for test it works
Console.WriteLine(DateTime.UtcNow);
//check my messages
}
}
This doesn't work because it never goes inside TimerElapsed. What am I doing wrong?
Thank you
EDIT: even as a field timer doesn't goes inside elapsed event.
EDIT2: well, I found my problem. I was testing the TimerElapsed with a Console.WriteLine(DateTime.UtcNow) inside of it and it only works if i put after all the code on Init a Console.ReadLine(); Ill edit my code again to show it. I don't understad why I need this readLine so if someone could explain to me would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您不喜欢
ReadLine()
方法,您可以使用如下的轮询循环:这将使应用程序保持活动状态,直到用户按下 Escape 键。
您应该会看到以您指定的任何时间间隔打印的时间戳。
If you don't like the
ReadLine()
approach, you can use a polling loop like this instead:This will keep the app alive until the user hits the Escape key.
You should see the timestamps printing at whatever interval you specified.