Possible Duplicate:
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on
Below is a method that I’ve written which attempts to obtain the text from a RichTextControl and return it.
/** @delegate */
private delegate string RichTextBoxObtainContentsEventHandler();
private string ObtainContentsRichTextBox()
{
if (richtxtStatus.InvokeRequired)
{
// this means we're on the wrong thread!
// use BeginInvoke or Invoke to call back on the
// correct thread.
richtxtStatus.Invoke(
new RichTextBoxObtainContentsEventHandler(ObtainContentsRichTextBox)
);
return richtxtStatus.Text.ToString();
}
else
{
return richtxtStatus.Text.ToString();
}
}
However when I attempt to run this I get the following exception:
Cross-thread operation not valid: Control ‘richtxtStatus’ accessed from a thread other than the thread it was created on.
How can I modify the above code to allow me to return the contents?
The problem is that you are still accessing the text box on the wrong thread. You need to return the result of the
Invoke(), rather than just invoking, ignoring the result, and then doing the very thing you were trying to avoid in the first place. Also, you don’t need to wrap it in an event handler; just invoke the current method again.Finally,
.Textis already a string, so there’s no need to call.ToString()on it. It can be returned directly.