10

What is the difference between InvokeRequired and somecontrol.InvokeRequired?

like this,

delegate void valueDelegate(string value);

private void SetValue(string value)
{
   if (InvokeRequired)
   {
       BeginInvoke(new valueDelegate(SetValue),value);
   }
   else
   {
       someControl.Text = value;
   }
}

and

delegate void valueDelegate(string value);

private void SetValue(string value)
{   
    if (someControl.InvokeRequired)
    {
        someControl.Invoke(new valueDelegate(SetValue),value);
    }
    else
    {
        someControl.Text = value;
    }
}
Deanna
  • 23,876
  • 7
  • 71
  • 156

3 Answers3

20

The first version checks the thread responsible for this control. The second version checks the thread responsible for someControl. (And ditto for which control's thread they then delegate the invocation to.)

They could potentially be different - although they really shouldn't be if the two controls are in the same top-level window. (All controls in one window should be running on the same thread.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

The difference is the control of which you accessing the property. If you access InvokeRequired from within a method on the form, you're effectively access the form's InvokeRequired property.

If the form and the someControl are created in the same thread, then they will return the same value.

Dave Van den Eynde
  • 17,020
  • 7
  • 59
  • 90
2

It would seem that you in the first example are within the scope of a control, while in the second you are not. The main form is a control just like any other. If someControl is added to the Control collection of the main control, you may use either.

Øyvind Skaar
  • 1,842
  • 14
  • 22