首页 >后端开发 >C++ >如何用 C# 创建精确可靠的计时器?

如何用 C# 创建精确可靠的计时器?

Linda Hamilton
Linda Hamilton原创
2025-01-18 17:52:13183浏览

How Can I Create a Precise and Reliable Timer in C#?

用 C# 构建高精度、可靠的计时器

为了在 C# 中创建高度准确且可靠的计时器,System.Timers.Timer 类提供了强大的解决方案。此类允许您按特定时间间隔安排任务。

Interval 对象的 Timer 属性设置计时器事件之间的时间。 将此值设置为 15000 毫秒(15 秒)会每 15 秒触发关联的方法。

下面是展示 Timer 类的代码示例:

<code class="language-csharp">using System;
using System.Timers;

public class TimerExample
{
    public static void Main(string[] args)
    {
        // Create a timer with a 15-second interval
        Timer timer = new Timer(15000); 
        timer.Elapsed += OnTimedEvent; // Attach the event handler
        timer.Start(); // Start the timer

        Console.WriteLine("Press 'q' to exit.");
        while (Console.ReadKey().Key != ConsoleKey.Q) { } // Keep the console app running
    }

    // Method executed when the timer elapses
    private static void OnTimedEvent(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("Timer event triggered.");
    }
}</code>

此代码创建一个计时器,每 15 秒调用一次 OnTimedEvent 方法。 Console.ReadKey() 方法使控制台应用程序保持运行,直到用户按“q”。

以上是如何用 C# 创建精确可靠的计时器?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn