I’ve read up some of the basics on using delegates here
I posted a question on SO and the following code was part of the answer.
Can this syntax be converted into syntax more like the MSDN article where a delegate is explicitly declared etc. or in certain circumstance is this the only way of coding it?
The reason I’m looking for an alternative way of coding it is that as a newbie to c# I find this line difficult to get my head around this.BeginInvoke(new MethodInvoker(delegate
private void myTimer_Elapsed(Object myObject,EventArgs myEventArgs){
elapsedCounter++;
elapsedTime = DateTime.Now.Subtract(startTime);
if (elapsedTime.TotalMilliseconds < MaxTime)
{
this.BeginInvoke(new MethodInvoker(delegate
{
this.lblElapsedTime.Text = elapsedTime.ToString();
if (elapsedCounter % 2 == 0)
this.lblValue.Text = EvenText;
else
this.lblValue.Text = OddText;
}));
}
else
{
myTimer.Stop();
myTimer.Dispose();
//myProcess.Close();
}
}
MethodInvokeris just a predefined delegate which takes no parameters and returnsvoid:You are perfectly free to create your own delegate instead, just like in the example you linked to:
and replace
MethodInvokerwithMyDelegate.In your code, an anonymous method is created. The advantage of the anonymous method is that it could access local variables declared in
myTimer_Elapsed. SinceelapsedTimeandelapsedCounterseem to be declared outside, you could replace this with an explicitly defined method as follows: