Click here to Skip to main content
15,890,557 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How does one correct this?

Cross-thread operation not valid: Control 'rtb' accessed from a thread other than the thread it was created on.
Posted
Comments
Sergey Alexandrovich Kryukov 1-May-11 15:47pm    
Tag it! WPF, Forms, what?!
--SA

1 solution

Check out Control.InvokeRequired[^] from MSDN.

Basic you do:

private void DisplayString(string index)
{
  if (this.InvokeRequired)
  {
    this.Invoke(new Action(() => DisplayString(index)));
    return;
  }
  this.textBox_Index.Text = index;
}


InvokeRequired tells if the caller is from another thread then where the TextBox was created. If it is true.
We have to Invoke to the same thread before we can change the TextBox.

WinForms UI Thread Invokes: An In-Depth Review of Invoke/BeginInvoke/InvokeRequre[^]
 
Share this answer
 
v2
Comments
Member 7766180 1-May-11 14:12pm    
Thank You Kim!
DS
Kim Togo 1-May-11 15:03pm    
Your are welcome.
Sergey Alexandrovich Kryukov 1-May-11 15:49pm    
Yes, that's it, my 5. Well, InvokeRequred is rarely needed, as developers often know it's not UI thread. Dispatcher would be better as OP did not specify Forms or WPF or what.
--SA
Kim Togo 2-May-11 2:29am    
Thanks SA. You a right about InvokeRequred is rarely needed.
But if you what to make a method "Thread-safe" in a UI control. InvokeRequred is a good thing.
Sergey Alexandrovich Kryukov 2-May-11 3:58am    
No! It would be just a waste of time. Not a mistake of course, but calling Invoke/BeginInvoke is not a mistake as well, so let's consider the perfect solution.

InvokeRequired will always return false if called from UI thread, always true otherwise.
Invoke will work in both cases.

Therefore, InvokeRequired should be used only in the method which can be called from both UI and non-UI thread; in all other cases it should be always Invoke/BeginInvoke (non-UI thread) or a direct call (UI thread). I considered all three cases -- final answer.

--SA

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