Click here to Skip to main content
15,909,822 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi i am calling a function but it is giving me error:
Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.
plz help

C#
private void button1_Click(object sender, System.EventArgs e)
        {
            _t = new Thread(new ThreadStart(DoSomething));
            _t.Start();
        }
private Thread _t;
        private void DoSomething()
        {
            try
            {
                while(true)
                {
                   write(str);
                }
            }
            catch (ThreadAbortException ex)
            {
                MessageBox.Show("Loop break");
                return;
            }
        }
 public void WriteText(string str)
{
/*do something*/
}

 private void button2_Click(object sender, System.EventArgs e)
  {
            _t.Abort();
  }
Posted
Updated 11-Sep-12 3:51am
v2
Comments
[no name] 11-Sep-12 9:55am    
Would you accept help from someone other than "plz"?
Member 9092048 11-Sep-12 9:56am    
yes

Hi,

you can try this code:
C#
private delegate void WriteTextCallback(string str);
public void WriteText(string str)
{
   if (this.InvokeRequired)
   {
      BeginInvoke(new WriteTextCallback(WriteText), new object[] { str });
      return;
   }
   TextBox1.Text = "Hallo";
}
 
Share this answer
 
Comments
Espen Harlinn 11-Sep-12 10:09am    
5'ed!
Member 9092048 11-Sep-12 10:40am    
thanks
RaisKazi 11-Sep-12 15:59pm    
My 5!
UI controls can only be accessed from the thread they are created on (the UI thread). If you try to do so from a different thread, you get the error.
You need to Invoke the control. Here is a generic way to do it:
C#
private void AddNewTab(string tabName)
    {
    if (InvokeRequired)
        {
        Invoke(new MethodInvoker(delegate { AddNewTab(tabName); }));
        }
    else
        {
        TabPage tp = new TabPage(tabName);
        myTabControl.TabPages.Add(tp);
        }
    }
 
Share this answer
 
Comments
Espen Harlinn 11-Sep-12 10:09am    
5'ed!
RaisKazi 11-Sep-12 16:00pm    
My 5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900