當前位置: 首頁>>代碼示例>>C#>>正文


C# Timer類代碼示例

本文整理匯總了C#中System.Timers.Timer的典型用法代碼示例。如果您正苦於以下問題:C# Timer類的具體用法?C# Timer怎麽用?C# Timer使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Timer類屬於System.Timers命名空間,在下文中一共展示了Timer類的4個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: Main

//引入命名空間
using System;
using System.Timers;

public class Example
{
   private static System.Timers.Timer aTimer;
   
   public static void Main()
   {
      SetTimer();

      Console.WriteLine("\nPress the Enter key to exit the application...\n");
      Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);
      Console.ReadLine();
      aTimer.Stop();
      aTimer.Dispose();
      
      Console.WriteLine("Terminating the application...");
   }

   private static void SetTimer()
   {
        // Create a timer with a two second interval.
        aTimer = new System.Timers.Timer(2000);
        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;
        aTimer.AutoReset = true;
        aTimer.Enabled = true;
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                          e.SignalTime);
    }
}
開發者ID:.NET開發者,項目名稱:System.Timers,代碼行數:37,代碼來源:Timer

輸出:

Press the Enter key to exit the application...

The application started at 09:40:29.068
The Elapsed event was raised at 09:40:31.084
The Elapsed event was raised at 09:40:33.100
The Elapsed event was raised at 09:40:35.100
The Elapsed event was raised at 09:40:37.116
The Elapsed event was raised at 09:40:39.116
The Elapsed event was raised at 09:40:41.117
The Elapsed event was raised at 09:40:43.132
The Elapsed event was raised at 09:40:45.133
The Elapsed event was raised at 09:40:47.148

Terminating the application...

示例2: Main

//引入命名空間
using System;
using System.Threading.Tasks;
using System.Timers;

class Example
{
   static void Main()
   {
      Timer timer = new Timer(1000);
      timer.Elapsed += async ( sender, e ) => await HandleTimer();
      timer.Start();
      Console.Write("Press any key to exit... ");
      Console.ReadKey();
   }

   private static Task HandleTimer()
   {
     Console.WriteLine("\nHandler not implemented..." );
     throw new NotImplementedException();
   }
}
開發者ID:.NET開發者,項目名稱:System.Timers,代碼行數:22,代碼來源:Timer

輸出:

Press any key to exit...
Handler not implemented...

Unhandled Exception: System.NotImplementedException: The method or operation is not implemented.
at Example.HandleTimer()
at Example.<
b__0>d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c__DisplayClass2.b__5(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() at System.Threading.ThreadPoolWorkQueue.Dispatch()

示例3: new Timer()

//引入命名空間
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

public class Form1 : System.Windows.Forms.Form {
    public System.Timers.Timer timer1;
    private System.Windows.Forms.Label label1;
    public Form1() {
        this.timer1 = new System.Timers.Timer();
        this.label1 = new System.Windows.Forms.Label();
        ((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
        this.SuspendLayout();
        // 
        // timer1
        // 
        this.timer1.Enabled = true;
        this.timer1.SynchronizingObject = this;
        this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimerElapsed);
        // 
        // label1
        // 
        this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
        this.label1.ForeColor = System.Drawing.SystemColors.Highlight;
        this.label1.Location = new System.Drawing.Point(24, 8);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(224, 48);
        this.label1.TabIndex = 0;
        this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
        // 
        // Form1
        // 
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(292, 69);
        this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                      this.label1});
        this.Text = "My Clock";
        this.Load += new System.EventHandler(this.Form1_Load);
        ((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
        this.ResumeLayout(false);

    }
    [STAThread]
    static void Main() {
        Application.Run(new Form1());
    }

    private void Form1_Load(object sender, System.EventArgs e) {
        timer1.Interval = 1000;
        timer1.Start();
        timer1.Enabled = true;
    }

    private void OnTimerElapsed(object sender, System.Timers.ElapsedEventArgs e) {
        label1.Text = DateTime.Now.ToString();
    }
}
開發者ID:C#程序員,項目名稱:System.Timers,代碼行數:60,代碼來源:Timer

示例4: new Timer(new TimerCallback(TimerHandler), null, 5000, 10000)

//引入命名空間
using System;        
using System.Threading;

public class MainClass
{
  public static AutoResetEvent A = new AutoResetEvent(false);
  public static int index = 0;
  
  public static int Main(){
    Timer T = new Timer(new TimerCallback(TimerHandler), null, 5000, 10000);

    A.WaitOne();
    Console.WriteLine("Main Thread event signaled");
    T.Dispose();
    return 0;
  }
  public static void TimerHandler(object state)
  {
    Console.WriteLine("TimerHandler");
    if (index == 5)
      A.Set();

    index++;
    Console.WriteLine(index);
  }
}
開發者ID:C#程序員,項目名稱:System.Timers,代碼行數:27,代碼來源:Timer


注:本文中的System.Timers.Timer類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。