Let's say I have the following code:
var secondsElapsed = 0;
Timer myTimer = new Timer();
myTimer.Elapsed += new ElapsedEventHandler( iterateSecondsElapsed);
myTimer.Interval = 1000;
myTimer.Start();
//Somewhere else in the code:
public static void iterateSecondsElapsed( object source, ElapsedEventArgs e )
{
secondsElapsed++;
}
Is there any way to do this WITHOUT defining the DisplayTimEvent static method? Something like:
myTimer.Elapsed += new ElapsedEventHandler( secondsElapsed => secondsElapsed ++);
I realize I am showing a profound lack of understanding of lambdas here, but nonetheless...
Sure, just:
myTimer.Elapsed += (sender, args) => secondsElapsed++;
The parameters for the lambda expression have to match the parameters for the delegate that you're trying to convert it to, basically.
Depending on whether the Timer
you're using always fires on the same thread or not, you may want to use:
myTimer.Elapsed += (sender, args) => Interlocked.Increment(ref secondsElapsed);
myTimer.Elapsed += (sender, e) => {secondsElapsed++;};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With