In the code from this link: http://c-sharp-programming.blogspot.com/2008/07/cross-thread-operation-not-valid.html, a delegate is used to update a text box’s value from a worker thread.
I can basically see what’s happening, but the syntax of this line specifically:
label1.Invoke(del, new object[] { newText });
is confusing to me. Can someone explain it please? Why do we use a new object array syntax for the delegate when there’s only one parameter?
Full code:
delegate void updateLabelTextDelegate(string newText);
private void updateLabelText(string newText)
{
if (label1.InvokeRequired)
{
// this is worker thread
updateLabelTextDelegate del = new updateLabelTextDelegate(updateLabelText);
label1.Invoke(del, new object[] { newText });
}
else
{
// this is UI thread
label1.Text = newText;
}
}
TL;DR:
Control.Invokeis calling DynamicInvoke on your delegate which takes an object array of parameters to work with any delegate type.//
The keyword delegate in C# in analagous to specifying a type of function pointer. You can use that type to pass methods of a specific signature. In your example, the signature is for a method that takes 1 arg (a string) and returns nothing (void). The method
updateLabelTextmatches that sig. The line:Is just a full-text way of saying:
Then, you can pass your variable
del, which is now a pointer to the methodupdateLabelTextto theControl.Invokemethod.Which thanks to
paramsbeing using in theControl.Invokesignature, you don’t even have to explicitly say it’s anobject[]The
Invoketakes an array of objects, which it’ll use as the args to the delegate given. (Yes your update method takes one string arg, keep reading) With your variabledel, you could callupdateLabelTextyourself:Which would essentially be the same as:
Inside
Control.Invoke, they are calling yourdelmethod, but it doesn’t have to know how many args it takes thanks to some helper methods on delegates. You would find something like this:EDIT I did some deep digging for science, the invocation internally is more like:
Where
argsis anobject[]. For more info on things you can do with your delegate variable (which is of type Delegate), read more here.