C # Timer with Lambda instead of method reference?

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 a static DisplayTimEvent method? Sort of:

 myTimer.Elapsed += new ElapsedEventHandler( secondsElapsed => secondsElapsed ++); 

I understand that I'm showing a deep lack of understanding of lambda here, but nonetheless ...

+5
source share
2 answers

Of course, just:

 myTimer.Elapsed += (sender, args) => secondsElapsed++; 

The parameters for the lambda expression should match the parameters for the delegate to which you are trying to convert it, basically.

Depending on whether the Timer you are using is always running in the same thread or not, you can use:

 myTimer.Elapsed += (sender, args) => Interlocked.Increment(ref secondsElapsed); 
+11
source
 myTimer.Elapsed += (sender, e) => {secondsElapsed++;}; 
+4
source

Source: https://habr.com/ru/post/1242785/


All Articles