0

Can someone explain me what this System.Timer does with the ElapsedEventHandler? I don't understand this syntax:

private readonly System.Timers.Timer _timer7 = new System.Timers.Timer();
this._timer7.Elapsed += (ElapsedEventHandler) ((A_1, A_2) =>
      {
        this._logger.LoggingOfError("T7-Timeout");
      });
gunr2171
  • 16,104
  • 25
  • 61
  • 88
Josh
  • 287
  • 1
  • 8
  • funny I asked the exact same question 3 years ago..... [here I found it](https://stackoverflow.com/questions/37679480/please-explain-timer-event-async-await-syntax). It's about an async handler, but basically I had the same question about the syntax. If it answers your question, I can mark it as duplicate – Mong Zhu Sep 19 '19 at 14:27

2 Answers2

0

The code of your question is the same as:

_timer7.Elapsed += (sender, e) =>
{
  _logger.LoggingOfError("T7-Timeout");
};

And that is the same as:

_timer7.Elapsed += _timer7_Elapsed;

private void _timer7_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
  _logger.LoggingOfError("T7-Timeout");
}

You can have explanations about anonymous methods here:

What are anonymous methods in C#?

0

System.Timers.Elapsed is type of ElapsedEventHandler which defined as below:

public delegate void ElapsedEventHandler(object sender, ElapsedEventArgs e);

the delegate registered for _timer7.Elapsed is a Lambda Expression (anonymous method).

A_1 is sender, and A_2 is e.

As a result, when _timer7.Elapsed will fired, the anonymous method with arguments A_1 as sender, and A_2 as e, will be called.
That will lead the line this._logger.LoggingOfError("T7-Timeout"); to be execute

Roni
  • 369
  • 1
  • 7
  • 22