在winform编程时在主线程中添加一个textbox控件,然后再创建一个线程,在这个线程开始后,怎么在这个线程的函数中修改textbox的text属性,我每次编译都报错:Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.
这是怎么回事啊
好像在子线程中修改任何一个主线程创建的控件的属性都这样,但是修改主线程的变量是可以的
求各位高手帮帮忙·!!!!!

解决方案 »

  1.   

    就是这样的,不能直接跨线程调用控件了,必须通过delegate
    比如private delegate void ReportConditionReceived(int iteration, double error);在另外的那个线程里面这样写
    form1.Invoke(new ReportConditionReceived(this.ShowCondition), e.Iteration, e.Error);主线程里面就可以这样写了
    private void ShowCondition(int iteration, double error)
    {
    this.labelIteration.Text = iteration.ToString();
    this.labelError.Text = error.ToString();
    }
      

  2.   

    参看
    http://blog.csdn.net/knight94/archive/2006/03/16/626584.aspx
      

  3.   

    你必须在创建ui的线程上来操作UI,而不能使用另外的线程,否则会出错.你可以看看Control.BeginInvoke方法的用法.
      

  4.   

    private void InvokeFun()
            {
    yourTextBox.Text = "***";//Set your text box value here
            }// in your sub thread function
                //Create invoke method by specific function            MethodInvoker mi = new MethodInvoker( this.InvokeFun );            this.BeginInvoke( mi );
      

  5.   

    用委托函数是完全可以的。
    不过刚才没有委托,好像也可以实现了。各位大侠,我们说的是一种情况吗? public class Form1 : System.Windows.Forms.Form
    {
    private int count = 0;
    private Thread t = null; //... [STAThread]
    static void Main() 
    {
    Application.Run(new Form1());
    } private void btnStart_Click(object sender, System.EventArgs e)
    {
    try
    {
    t = new System.Threading.Thread(new ThreadStart(SetText));
    t.Start();
    }
    catch (Exception ex)
    {
    count = 0;
    }
    } public void SetText()
    {
    try
    {
    while (count < 1000) // condition
    {
    count ++;
    txtCount.Text = count.ToString(); //txtCount 为一TextBox控件
    Thread.Sleep(100);
    }
    }
    catch (Exception ex)
    {
    }
    }
    }