首頁 >後端開發 >C++ >如何用 C# 建立精確可靠的計時器?

如何用 C# 建立精確可靠的計時器?

Linda Hamilton
Linda Hamilton原創
2025-01-18 17:52:13204瀏覽

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