C# のタイマー
    
    Muhammad Maisam Abbas
    2024年2月16日
    
    Csharp
    Csharp Timer
    
 
このチュートリアルでは、C# でタイマーを作成する方法について説明します。
C# で Timer クラスを使用してタイマーを作成する
    
Timer クラスは、C# で設定された時間間隔の後にイベントを作成するために使用されます。C# の Timer クラスを使用して、指定した時間が経過すると繰り返されるイベントを生成できます。Timer.Elapsed イベントは、繰り返すイベントを指定するために使用されます。次のコード例は、C# の Timer クラスを使用して、指定された時間間隔の後にイベントを繰り返すタイマーを作成する方法を示しています。
using System;
using System.Timers;
namespace timer {
  class Program {
    private static void OnTimedEvent(object source, ElapsedEventArgs e) {
      Console.WriteLine("Hello World!");
    }
    static void Main(string[] args) {
      System.Timers.Timer myTimer = new System.Timers.Timer();
      myTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
      myTimer.Interval = 500;
      myTimer.Enabled = true;
      Console.WriteLine("Press \'e\' to escape the sample.");
      while (Console.Read() != 'e')
        ;
    }
  }
}
出力:
Press 'e' to escape the sample.
Hello World!
e
上記のコードでは、出力 Hello World!を繰り返すタイマーを作成しました。文字 e が C# に入力されるまで、500 ミリ秒ごとに。最初に、Timer クラスのインスタンス myTimer を初期化しました。次に、OnTimedEvent() 関数を Time.Elapsed イベントのイベントとして指定しました。間隔は、myTimer.Interval プロパティを使用して 500 ミリ秒に設定されます。最後に、myTimer.Enabled プロパティを使用してタイマーを開始しました。
        チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe
    
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn