Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Timer With Lambda Instead of Method Reference?

Tags:

c#

lambda

timer

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...

like image 318
VSO Avatar asked Feb 11 '16 14:02

VSO


2 Answers

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);
like image 136
Jon Skeet Avatar answered Oct 27 '22 09:10

Jon Skeet


myTimer.Elapsed += (sender, e) => {secondsElapsed++;};
like image 45
Sophie Coyne Avatar answered Oct 27 '22 10:10

Sophie Coyne