C# winform三種定時方法
阿新 • • 發佈:2018-12-24
1. 直接用winform 的 timers
拖控制元件進去 程式碼 public partial class Form1 : Form { public Form1() { InitializeComponent(); } int sum = 0; int qian; int bai; int shi; int ge; private void Form1_Load(object sender, EventArgs e)//初始化 { textBox1.Text = "00.00"; timer1.Interval = 1000; timer1.Stop(); } private void button1_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.Owner = this; this.Hide(); f2.Show(); //窗體2返回在窗體2寫程式碼 this.Hide(); this.Owner.Show(); } private void button2_Click(object sender, EventArgs e) { timer1.Start(); } private void timer1_Tick(object sender, EventArgs e)//winform的timer,不精確 { sum++; qian = sum / 1000; bai = sum % 1000 / 100; shi = sum % 100 / 10; ge = sum % 10; textBox1.Text = qian.ToString() + bai.ToString() + "." + shi.ToString() + ge.ToString(); } 2.使用System.Timers.Timer 先定義System.Timers.Timer t; private void Form1_Load(object sender, EventArgs e)//初始化 { textBox1.Text = "00.00"; t = new System.Timers.Timer(1000); t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到達時間的時候執行事件; t.AutoReset = true;//設定是執行一次(false)還是一直執行(true); } private void button2_Click(object sender, EventArgs e) { t.Enabled = true;//是否執行System.Timers.Timer.Elapsed事件; //如果不寫下面這句會有一個異常。 //異常:執行緒間操作無效: 從不是建立控制元件"richtextbox"的執行緒訪問它 //但這不是最好的方法。如果只有一個程序呼叫richtextbox而已。就可以用下面這句 //如果有多個執行緒呼叫richtextbox等控制元件。就要用委託。見thread第二種方法 Control.CheckForIllegalCrossThreadCalls = false; } private void theout(object sender, EventArgs e) { sum++; qian = sum / 1000; bai = sum % 1000 / 100; shi = sum % 100 / 10; ge = sum % 10; textBox1.Text = qian.ToString() + bai.ToString() + "." + shi.ToString() + ge.ToString(); } 3.thread Thread th;//定義執行緒 private void Form1_Load(object sender, EventArgs e)//初始化 { textBox1.Text = "00.00"; th=new Thread(calculate); th.IsBackground = true; } private void button2_Click(object sender, EventArgs e) { th.Start(); //Control.CheckForIllegalCrossThreadCalls = false; 同2,不寫會報錯 } private void calculate()//執行緒的第一種方法 { while(true) { sum++; qian = sum / 1000; bai = sum % 1000 / 100; shi = sum % 100 / 10; ge = sum % 10; textBox1.Text = qian.ToString() + bai.ToString() + "." + shi.ToString() + ge.ToString(); Thread.Sleep(1000); } } 下面第二種方法: private delegate void FlushClient();//定義委託 private void Form1_Load(object sender, EventArgs e)//初始化 { textBox1.Text = "00.00"; th = new Thread(CrossThreadFlush);//執行緒第二種方法 th.IsBackground = true; } private void CrossThreadFlush()//第二種方法 { while (true) { Thread.Sleep(1000); ThreadFunction(); } } private void ThreadFunction()//第二種方法 { if (this.textBox1.InvokeRequired)//等待非同步 { FlushClient fc = new FlushClient(ThreadFunction); this.Invoke(fc);//通過代理呼叫重新整理方法 } else { sum++; qian = sum / 1000; bai = sum % 1000 / 100; shi = sum % 100 / 10; ge = sum % 10; textBox1.Text = qian.ToString() + bai.ToString() + "." + shi.ToString() + ge.ToString(); } }