gpt4 book ai didi

c# - 如何在 C# 中每隔特定时间间隔触发一个事件?

转载 作者:行者123 更新时间:2023-11-30 19:40:51 28 4
gpt4 key购买 nike

定时器需要作为一个线程运行,它会每隔固定的时间间隔触发一个事件。我们如何在 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com