Inside a class I have got a TextBox:
public class TextBoxAdapter {
private System.Windows.Forms.TextBox textBox;
//...some code that initializes the textBox...
public string getTextFromBox() {
if( textBox.InvokeRequired )
return (string)textBox.Invoke( (Func<string>)delegate { return textBox.Text; } );
else
return textBox.Text;
}
}
To access this TextBox safely from another Thread I would like to use the Invoke mechanism. But the function getTextFromBox()
fails at the line where Invoke()
is used. I verified this by putting a breakpoint at this line and pressing F10 (Step over). It fails without an exception. Is there a mistake at my way of invoking?
Edit
Why do I need to access a text box from another thread? I am trying to create a new thread on every button click to prevent my UI from freezing. E.g. on a user login window when the login button is pressed, a new thread is started that notifys and observer. The observer then wants to read the the values of the username- and password-textbox to check if the logintry is valid.
The strange thing about this: Writing to a textbox works without any problem. The code I use:
if ( textBox.InvokeRequired ) {
MethodInvoker setText = new MethodInvoker( () => {
textBox.Text = text;
} );
textBox.BeginInvoke( setText );
}
else {
textBox.Text = text;
}