使用委託及控制元件的invoke方法處理窗體控制元件的跨執行緒訪問

iamzxf發表於2015-06-02


namespace thread2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private Thread threadb;

        delegate void setText(string s);
        setText ST;


        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = "0";
            ST = new setText(setLabelText);
            
        }
       
        private void setLabelText(string s)
        {
            label1.Text = s;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            threadb = new Thread(new ThreadStart(runner));
            threadb.Start();
        }

        private void runner()
        {
            for (int i = 0; i <= 100; i++)
            { 
                label1.Invoke(ST, new object[]{i.ToString()});
                Thread.Sleep(500);
            }
        }
        private void thread2_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (threadb.IsAlive)
                threadb.Abort();
        }
    }
}



相關文章