c#跨线程操作控件(有UI操作)|及多线程操作

跨线程操作UI控件

※在.NET2.0之后为了线程之间的安全,不允许跨线程操作控件,最简单的解决办法是禁止检查,但一般不猜用此方法,会造成各线程之间的混乱,可用作临时调试使用。

public Form1()
{
  InitializeCompoent();
  Control.CheckForIllegalCrossThreadCalls=false;
}

①跨线程操作UI控件

■测试实现的功能,单击按钮(button1),实现文本(label1)从0到100的自增

复制代码
        private void button1_Click(object sender, EventArgs e)
        {
            Thread pThread = new Thread(new ThreadStart(this.ThreadProcSafe));
            pThread.Start();
        }
        public delegate void StringArgReturningVoidDelegate(string str);
        private void ThreadProcSafe()
        {
            for (int i = 0; i < 100; i++)
            {
                SetText(i.ToString());
                Thread.Sleep(100);
            }
        }
        private void SetText(string str)
        {
            if (this.label1.InvokeRequired)
            {
                StringArgReturningVoidDelegate d = new StringArgReturningVoidDelegate(SetText);
                this.Invoke(d, new object[] { str });
            }
            else
            {
                this.label1.Text = str;
            }
        }
复制代码

②多线程,无UI操作

■使用backgroundWorker控件

复制代码
        private void button1_Click(object sender, EventArgs e)
        {
            using (BackgroundWorker bw = new BackgroundWorker())
            {
                bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_complete);
                bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                bw.RunWorkerAsync("SQYJ");
            }
        }
        public void bw_complete(object secder, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("cs");
        }

        public void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(1000);
            e.Result = e.Argument;
        }
欢迎评论。
lingkb » c#跨线程操作控件(有UI操作)|及多线程操作

发表评论