c#中定時器的實現。

來源:互聯網
上載者:User

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();        }    }}

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.