web-dev-qa-db-ja.com

C#コンソールアプリケーションにタイマーを追加する方法

これだけ-タイマーをC#コンソールアプリケーションに追加するにはどうすればよいですか?コーディング例を提供できれば素晴らしいと思います。

125
Johan Bresler

これは非常に素晴らしいことですが、時間が経過するのをシミュレートするには、時間がかかるコマンドを実行する必要があり、2番目の例では非常に明確です。

ただし、forループを使用して何らかの機能を永久に実行するスタイルでは、多くのデバイスリソースが必要になり、代わりにガベージコレクターを使用してそのようなことを行うことができます。

この変更は、同じ本CLR Via C#Third Edのコードで見ることができます。

using System;
using System.Threading;

public static class Program {

   public static void Main() {
      // Create a Timer object that knows to call our TimerCallback
      // method once every 2000 milliseconds.
      Timer t = new Timer(TimerCallback, null, 0, 2000);
      // Wait for the user to hit <Enter>
      Console.ReadLine();
   }

   private static void TimerCallback(Object o) {
      // Display the date/time when this method got called.
      Console.WriteLine("In TimerCallback: " + DateTime.Now);
      // Force a garbage collection to occur for this demo.
      GC.Collect();
   }
}
118

System.Threading.Timerクラスを使用します。

System.Windows.Forms.Timerは、主に単一のスレッド(通常はWindows Forms UIスレッド)で使用するために設計されています。

.NETフレームワークの開発の早い段階で追加されたSystem.Timersクラスもあります。ただし、これはSystem.Threading.Timerのラッパーであるため、代わりにSystem.Threading.Timerクラスを使用することをお勧めします。

Windowsサービスを開発していて、タイマーを定期的に実行する必要がある場合は、常に静的(VB.NETで共有)System.Threading.Timerを使用することもお勧めします。これにより、タイマーオブジェクトのガベージコレクションが早すぎる可能性がなくなります。

コンソールアプリケーションのタイマーの例を次に示します。

using System; 
using System.Threading; 
public static class Program 
{ 
    public static void Main() 
    { 
       Console.WriteLine("Main thread: starting a timer"); 
       Timer t = new Timer(ComputeBoundOp, 5, 0, 2000); 
       Console.WriteLine("Main thread: Doing other work here...");
       Thread.Sleep(10000); // Simulating other work (10 seconds)
       t.Dispose(); // Cancel the timer now
    }
    // This method's signature must match the TimerCallback delegate
    private static void ComputeBoundOp(Object state) 
    { 
       // This method is executed by a thread pool thread 
       Console.WriteLine("In ComputeBoundOp: state={0}", state); 
       Thread.Sleep(1000); // Simulates other work (1 second)
       // When this method returns, the thread goes back 
       // to the pool and waits for another task 
    }
}

本から CLR Via C# Jeff Richterによる。ちなみに、この本では、第23章で強く推奨されている3種類のタイマーの背後にある理論的根拠を説明しています。

65
Ash

以下に、単純な1秒のタイマーティックを作成するコードを示します。

  using System;
  using System.Threading;

  class TimerExample
  {
      static public void Tick(Object stateInfo)
      {
          Console.WriteLine("Tick: {0}", DateTime.Now.ToString("h:mm:ss"));
      }

      static void Main()
      {
          TimerCallback callback = new TimerCallback(Tick);

          Console.WriteLine("Creating timer: {0}\n", 
                             DateTime.Now.ToString("h:mm:ss"));

          // create a one second timer tick
          Timer stateTimer = new Timer(callback, null, 0, 1000);

          // loop here forever
          for (; ; )
          {
              // add a sleep for 100 mSec to reduce CPU usage
              Thread.Sleep(100);
          }
      }
  }

結果の出力は次のとおりです。

    c:\temp>timer.exe
    Creating timer: 5:22:40

    Tick: 5:22:40
    Tick: 5:22:41
    Tick: 5:22:42
    Tick: 5:22:43
    Tick: 5:22:44
    Tick: 5:22:45
    Tick: 5:22:46
    Tick: 5:22:47

編集: CPUサイクルを無駄に消費するため、ハードスピンループをコードに追加することはお勧めできません。この場合、アプリケーションのクローズを停止するためだけにループが追加され、スレッドのアクションを監視できるようになりました。ただし、正確性とCPU使用率を削減するために、単純なスリープコールがそのループに追加されました。

21
jussij

少し楽しみましょう

using System;
using System.Timers;

namespace TimerExample
{
    class Program
    {
        static Timer timer = new Timer(1000);
        static int i = 10;

        static void Main(string[] args)
        {            
            timer.Elapsed+=timer_Elapsed;
            timer.Start();
            Console.Read();
        }

        private static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            i--;

            Console.Clear();
            Console.WriteLine("=================================================");
            Console.WriteLine("                  DIFFUSE THE BOMB");
            Console.WriteLine(""); 
            Console.WriteLine("                Time Remaining:  " + i.ToString());
            Console.WriteLine("");        
            Console.WriteLine("=================================================");

            if (i == 0) 
            {
                Console.Clear();
                Console.WriteLine("");
                Console.WriteLine("==============================================");
                Console.WriteLine("         B O O O O O M M M M M ! ! ! !");
                Console.WriteLine("");
                Console.WriteLine("               G A M E  O V E R");
                Console.WriteLine("==============================================");

                timer.Close();
                timer.Dispose();
            }

            GC.Collect();
        }
    }
}
14
Real Caz

または、短くて甘いRxを使用します。

static void Main()
{
Observable.Interval(TimeSpan.FromSeconds(10)).Subscribe(t => Console.WriteLine("I am called... {0}", t));

for (; ; ) { }
}
9
Yonatan Zetuny

少し制御したい場合は独自のタイミングメカニズムを使用することもできますが、精度が低くなり、コード/複雑さが増す可能性がありますが、タイマーをお勧めします。ただし、実際のタイミングスレッドを制御する必要がある場合は、これを使用します。

private void ThreadLoop(object callback)
{
    while(true)
    {
        ((Delegate) callback).DynamicInvoke(null);
        Thread.Sleep(5000);
    }
}

あなたのタイミングスレッドになります(必要に応じて、必要な時間間隔で停止するようにこれを変更します)。

使用/開始するには、次のことができます:

Thread t = new Thread(new ParameterizedThreadStart(ThreadLoop));

t.Start((Action)CallBack);

コールバックは、各間隔で呼び出されるvoidパラメーターなしメソッドです。例えば:

private void CallBack()
{
    //Do Something.
}
4
mattlant

独自に作成することもできます(使用可能なオプションに不満がある場合)

独自のTimer実装を作成することは非常に基本的なことです。

これは、他のコードベースと同じスレッドでCOMオブジェクトにアクセスする必要があるアプリケーションの例です。

/// <summary>
/// Internal timer for window.setTimeout() and window.setInterval().
/// This is to ensure that async calls always run on the same thread.
/// </summary>
public class Timer : IDisposable {

    public void Tick()
    {
        if (Enabled && Environment.TickCount >= nextTick)
        {
            Callback.Invoke(this, null);
            nextTick = Environment.TickCount + Interval;
        }
    }

    private int nextTick = 0;

    public void Start()
    {
        this.Enabled = true;
        Interval = interval;
    }

    public void Stop()
    {
        this.Enabled = false;
    }

    public event EventHandler Callback;

    public bool Enabled = false;

    private int interval = 1000;

    public int Interval
    {
        get { return interval; }
        set { interval = value; nextTick = Environment.TickCount + interval; }
    }

    public void Dispose()
    {
        this.Callback = null;
        this.Stop();
    }

}

次のようにイベントを追加できます。

Timer timer = new Timer();
timer.Callback += delegate
{
    if (once) { timer.Enabled = false; }
    Callback.execute(callbackId, args);
};
timer.Enabled = true;
timer.Interval = ms;
timer.Start();
Window.timers.Add(Environment.TickCount, timer);

タイマーが機能することを確認するには、次のように無限ループを作成する必要があります。

while (true) {
     // Create a new list in case a new timer
     // is added/removed during a callback.
     foreach (Timer timer in new List<Timer>(timers.Values))
     {
         timer.Tick();
     }
}
1
Steven de Salas