作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
定时器需要作为一个线程运行,它会每隔固定的时间间隔触发一个事件。我们如何在 C# 中做到这一点?
最佳答案
这是一个每 10 秒打印一条消息的简短片段。
using System;
public class AClass
{
private System.Timers.Timer _timer;
private DateTime _startTime;
public void Start()
{
_startTime = DateTime.Now;
_timer = new System.Timers.Timer(1000*10); // 10 seconds
_timer.Elapsed += timer_Elapsed;
_timer.Enabled = true;
Console.WriteLine("Timer has started");
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
TimeSpan timeSinceStart = DateTime.Now - _startTime;
string output = string.Format("{0},{1}\r\n", DateTime.Now.ToLongDateString(), (int) Math.Floor( timeSinceStart.TotalMinutes));
Console.Write(output);
}
}
关于c# - 如何在 C# 中每隔特定时间间隔触发一个事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21644006/
我是一名优秀的程序员,十分优秀!