I searched in google for a method which allows me to display a label for a specific time and I found this :
public void InfoLabel(string value)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(InfoLabel), new object[] { value });
return;
}
barStaticItem3.Caption = value;
if (!String.IsNullOrEmpty(value))
{
System.Timers.Timer timer = new System.Timers.Timer(6000) { Enabled = true };
timer.Elapsed += (sender, args) =>
{
this.InfoLabel(string.Empty);
timer.Dispose();
};
}
}
I really can’t understand this method specially :
-Why we used : InvokeRequired ?
-What this method for : this.Invoke() ?
-What this is for :new Action<string>(InfoLabel) ?
-Why we used that sign : => ?
InvokeRequiredchecks to see if the code is currently running on the thread that created the form. If it’s not then the function needs to invoke itself on the thread that DID create the form as WinForms code is not threadsafe.Action is a delegate type that describes a function that takes a string (see the InfoLabel funcion? That’s what it’s referring to).
The above is saying. Please create a new delegate of type Action from the function InfoLabel and invoke it using the thread that created this. When you invoke it pass the object ‘value’ to it. ie call InfoLabel(value) on the thread that created the form. Notice that it returns from the function directly afterwards so none of the ‘meat’ of the function is run on the wrong thread (we are on the wrong thread at this point, otherwise InvokeRequired would not have been true). When the function is run again by Invoke it will be on the right thread and InvokeRequired will be false so this bit of code will not be run.
The above code is assigning an anonymous method to the Elapsed event of the timer. The first bit (sender, args) is describing the parameters of the method, then
=>is saying ‘here comes the method’, followed by a block of code (all the stuff inside the brackets).