C#工作者線程執行控件刷新方法

方法一:

 

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // 重點

            Control.CheckForIllegalCrossThreadCalls = false;

        }


        private void Form1_Load(object sender, EventArgs e)
        {
            Thread thread = new Thread(ThreadFuntion);
            thread.IsBackground = true;
            thread.Start();
        }


        private void ThreadFuntion()
        {
            while (true)
            {
                this.textBox1.Text = DateTime.Now.ToString();
                Thread.Sleep(1000);
            }
        }
    }

 

 

 

方法二:

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

 

        private delegate void FlushClient();//代理
        private bool bShouldStop = false;

 

        // 開始按鈕
        private void button1_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(CrossThreadFlush);
            bShouldStop = false;

            thread.IsBackground = true;
            thread.Start();
        }

 

        // 結束按鈕
        private void button2_Click(object sender, EventArgs e)
        {
            bShouldStop = true;
        }

 

        // 線程函數
        private void CrossThreadFlush()
        {
            //將代理綁定到方法
            FlushClient fc = new FlushClient(ThreadFuntion);
            while (bShouldStop == false)
            {
                this.BeginInvoke(fc);
                Thread.Sleep(1000);
            }
           
        }

 

        // 運行刷新函數
        private void ThreadFuntion()
        {
            this.label1.Text = DateTime.Now.ToString();
            // 更多的刷新都可以放到這裏
            //
        }

       

    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章