c/s結構下定時器的實現
在c/s結構下我就是想把時間即時更新出來。我用個lable顯示出來。
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;namespace 計時器{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { label1.Text = DateTime.Now.ToString(); System.Timers.Timer t = new System.Timers.Timer(1000);//執行個體化Timer類,設定間隔時間為1000毫秒 就是1秒; t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到達時間的時候執行事件; t.AutoReset = true;//設定是執行一次(false)還是一直執行(true); t.Enabled = true;//是否執行System.Timers.Timer.Elapsed事件; } public void theout(object source, System.Timers.ElapsedEventArgs e) { this.Invoke(new TextOption(f));//invok 委託實現跨線程的調用 } delegate void TextOption();//定義一個委託 void f() { label1.Text = DateTime.Now.ToString();//調用內容,並用lable1顯示出來。。。 } }}
SilverLight中定時器的實現:
using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;using System.Windows.Threading;namespace Sample{ public partial class _94頁例子 : UserControl { public _94頁例子() { InitializeComponent(); DispatcherTimer timer = new DispatcherTimer(); //設定間隔1秒 timer.Interval = new TimeSpan(0, 0, 1); //建立事件處理 timer.Tick += new EventHandler(timer_Tick); //開始計時 timer.Start(); } void timer_Tick(object sender, EventArgs e) { tbkTimer.Text = "目前時間:" + DateTime.Now.ToLongTimeString(); } }}