I know you have to Invoke to do a cross thread update. But if Invoke isn't required can you call the code the same way you would if the Invoke were required?
So instead of this:
if(rtbSearchResults.InvokeRequired)
{
var ctuDelegate = new SearchResultsCrossThreadUpdate(SetSearchResultsRTB);
rtbSearchResults.Invoke(ctuDelegate, new object[] { resultString });
}
else
{
SetSearchResultsRTB(resultString);
}
Can I just do this and accept a performance penalty?
var ctuDelegate = new SearchResultsCrossThreadUpdate(SetSearchResultsRTB);
rtbSearchResults.Invoke(ctuDelegate, new object[] { resultString });
One problematic situation is the case that you want to access controls on a form that doesn't yet have a handle. For example, if you call some initialization function on a created form to fill the form's controls before showing the form.
In this case, calling Invoke on the controls will throw an InvalidOperationException.
Consider this form:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Test()
{
Action a = () => { textBox1.Text = "A"; };
textBox1.Invoke(a);
}
}
And this code calling the form
Form1 form = new Form1();
form.Test();
form.ShowDialog();
This will result in an exception because the Invoke is called on the TextBox while it doesn't have a handle yet.
Include a check for InvokeRequired and there will not be an exception.
public void Test()
{
Action a = () => { textBox1.Text = "A"; };
if (textBox1.InvokeRequired)
{
textBox1.Invoke(a);
}
else
{
a();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With