I want to show a text in a label for a particular time so I did a search on google and I found these two solutions :
The first solution is :
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(3000) { Enabled = true };
timer.Elapsed += (sender, args) =>
{
this.InfoLabel(string.Empty);
timer.Dispose();
};
}
}
The second solution :
private void ShowTextForParticularTime(String caption)
{
Timer t = new Timer { Interval = 5000, Enabled = true};
t.Tick += (sender, args) => OnTimerEvent(sender, args, caption);
}
private void OnTimerEvent(object sender, EventArgs e, String caption)
{
barStaticItem3.Caption = caption;
}
Could you please tell me the deffrence between the two solutions, and why we use this symbole “=>” , also I understood nothing from this line :
if (InvokeRequired)
{
this.Invoke(new Action<string>(InfoLabel), new object[] { value });
return;
}
Okay, there is a good amount to explain here.
There is no major differences between the two options you have shown. The reason they look different is because the first id declaring a delegate method (lambda expression) inside the public method, while the second is just creating an event handler. They do almost the exact same thing. Infact you can see that in the delegate method you have the tradition event handler prameters (object sender, EventArgs e). Personally I prefer the second solution because it looks cleaner to me.
Invoke Required is used to handle threading. In C# errors will be thrown if a thread that didn’t create a visual object tries to alter the visual object. To get around this we make a call to the thread that created the visual object by calling “Invoke”. The “InvokeRequired” property just tells us if the current thread did not create the visual object. You should always use this when you are threading or making delegate methods (because you can’t control the thread that runs them.)
I hope this brief explanation helps. Comment if it is unclear