Pages

Showing posts with label Visual Studio 2010. Show all posts
Showing posts with label Visual Studio 2010. Show all posts

Monday, September 27, 2010

Use Thread update Text of TextBox

วันนี้ทดลองเขียนโปรแกรมเล่น ๆ ดูเกี่ยวกับ Threading ของ C# เพราะว่าจำเป็นต้องนำ thread ไปใช้งาน
เพื่อให้มันทำงานเป็น backgroupd ของ program เพื่อใช้ในการตรวจสอบว่าจำนวนที่เราเคยโหลดมาไว้ กับจำนวนที่เกิดขึ้นใหม่ เท่ากันหรือไม่ ซื้อทั้งสองจำนวนนี้อยู่คนละ DB กัน

มาเริ่มกันเลย ^^


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; using System.Threading;  namespace WindowsFormsApplication1 {     public partial class Form1 : Form     {         Thread tWatchTime;         // delegate is used to communicate with UI Thread from a non-UI thread         public delegate void UpdateTextCallback(string message);         public Form1()         {             InitializeComponent();         }          private void Form1_Load(object sender, EventArgs e)         {                     }          private void timer1_Tick(object sender, EventArgs e)         {             textBox2.Text = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":"                 + DateTime.Now.Second.ToString();         }          private void button1_Click(object sender, EventArgs e)         {             try             {                 if (button1.Text == "Start")                 {                     tWatchTime = new Thread(WatchTime);                     tWatchTime.IsBackground = true;                     tWatchTime.Start();                      button1.Text = "Stop";                 }                 else                 {                     tWatchTime.Abort();                     button1.Text = "Start";                 }             }             catch (Exception ex)             {                 MessageBox.Show(ex.Message);             }         }          public void WatchTime()         {             while (tWatchTime.IsAlive)             {                 Thread.Sleep(5000);                 textBox1.BeginInvoke(new UpdateTextCallback(UpdateText), new object[] { DateTime.Now.Second.ToString() });             }         }          public void UpdateText(string msg)         {             textBox1.Text = msg;         }          //textBox1.BeginInvoke(new UpdateTextCallback(UpdateText), new object[] { i.ToString() });         //    }         //}           //private void UpdateText(string message)         //{         //    textBox1.Text = message;         //}     } }

แต่ในตัวอย่างนี้ผมใช้ Thread ไป set time ทุก ๆ 5 วินาที ก็เลยต้องสั่งให้มัน sleep(5000)

หลังจากผ่านไป 5 วิทนาที ก็ set Textbox1.text ให้โดยดึงเอา second มาแสดง (แต่ในภาพอาจจะไม่ตรงเพราะจะมีเวลาหน่วงในการ save picture)