user875234
user875234

Reputation: 2517

Can you always Invoke instead of checking InvokeRequired?

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 });

Upvotes: 4

Views: 389

Answers (1)

NineBerry
NineBerry

Reputation: 28499

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();
    }
}

Upvotes: 2

Related Questions