现在的位置: 首页 > 综合 > 正文

c# winform中子线程操作控件

2013年09月18日 ⁄ 综合 ⁄ 共 623字 ⁄ 字号 评论关闭

 

c# 2.0中 子线程是不可以操作组件的,因为组件是主线程生成的,一切在主线程中显式生成的线程都叫做子线程。方法有2中,下面给出委托的解决办法,这个最保险:

 

 public partial class Form1 : Form
    {
        public static TextBox tb;
        public Form1()
        {
            InitializeComponent();
            tb = this.textBox1;
        }

       
        private void button1_Click(object sender, EventArgs e)
        {
            Class1 c1 = new Class1();
            Thread t = new Thread(c1.test);
            t.Start();
        }

    }

 

 

namespace WindowsApplication1
{
    class Class1
    {
        private delegate void setTextDelegate(String str);

        private void setText(String str)
        {
            Form1.tb.Text = str;
        }

        public void test()
        {
            if (Form1.tb.InvokeRequired)
            {
                setTextDelegate s = new setTextDelegate(setText);
                Form1.tb.Invoke(s, new String[] { "123" });
            }
            else
            {
                Form1.tb.Text = "234";
            }
        }
    }
}

 

主要就是invoke方法的调用,这个方法是主线程生成的组件调用的。

抱歉!评论已关闭.