0
votes

This question has probably been asked a lot, a main point of my question(and thus part of the reason I'm posting this), is that I don't know what this format/syntax is even called, and thus have no idea what to look for. For reference, I have attached an example of this type of code in question. In this example, a Timer is using the syntax/functionality I'm not fully understanding, but I've seen this type of syntax used inother contexts. My goal is I would like to extrapolate/understand/utilize this functionality in a general context(not necessarily using a Timer). I understand how the code works functionally, every 2 seconds(approximately) the timer activates "OnTimedEvent", and that method is printing out that the info about the event(as shown at the bottom of this post). From what I understand, my timer("aTimer") is an object, and it has the variables such as "autoreset" and "Enabled" which are bools being set to 'true' in the code.

This is difficult to articulate, but what I'm not understanding is the syntax/'how' it works. For example I see "aTimer.Elapsed += OnTimedEvent" and I can see that the result is "OnTimedEvent" is being called when the "Elapsed" event occurs. The problem is I don't understand the back-end of it so I don't know how to apply this to other code I work with.

  • What does "+=" do? Is it attaching a method to be called whenever the event happens? Is this spawned in the same thread as the event, and can multiple methods be called this way(like doing Elapsed += ArbitrarySecondMethod), or is this overriding some response/method that is connected to "Elapsed" by default? What would even be the default response?
  • In the "OnTimedEvent", how are "source" and the elapsed events actually being passed to it?
  • I don't see how 'e.SignalTime' even gets past the compiler stage. How would "OnTimedEvent" even know a Timer object exists?
  • Also, with parameters passed to the "OnTimedEvent", is that (Object x, Args y) a standard format used in this kind of situation, what would I look up to learn more about how to use these types of 'add-on' methods(in a general context)

Code/Syntax in Question:

(Sorry that the format is odd, but I wanted to make sure I bolded the specific parts that I'm wanting to understand)

{

       aTimer.Elapsed += OnTimedEvent;

}

private static void OnTimedEvent(Object source, ElapsedEventArgs e)

{

       Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime);

}

Full Program for Reference:

class Program
{
    private static System.Timers.Timer aTimer;

    public static void Main()
    {
        SetTimer();

        Console.WriteLine("\nPress the Enter key to exit the application...\n");
        Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);
        Console.ReadLine();
        aTimer.Stop();
        aTimer.Dispose();

        Console.WriteLine("Terminating the application...");
    }

    private static void SetTimer()
    {
        // Create a timer with a two second interval.
        aTimer = new System.Timers.Timer(2000);
        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;
        aTimer.AutoReset = true;
        aTimer.Enabled = true;
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                          e.SignalTime);
    }
}

The code displays output like the following:

//       Press the Enter key to exit the application...
//
//       The application started at 09:40:29.068
//       The Elapsed event was raised at 09:40:31.084
//       The Elapsed event was raised at 09:40:33.100
//       The Elapsed event was raised at 09:40:35.100
//       The Elapsed event was raised at 09:40:37.116
//       The Elapsed event was raised at 09:40:39.116
//       The Elapsed event was raised at 09:40:41.117
//       ....(you get the point)
//       Terminating the application...
1
This is called "events" and Microsoft has a whole tutorial on it and is a fundamental aspect of object oriented/event-response programming. I think the answer is way too broad for SO.Ron Beyer
Here's a term you can use in searching "multicast delegate". Otherwise this is just typical C# event code.juharr
@juharr, that is exactly what I was looking for, don't know why I couldn't figure out the term for it. Thanks!Justin Finkelstein

1 Answers

1
votes

Flow:

create aTimer
find Main()
run SetTimer
init aTimer to 2000 milliseconds
set elapsed event to OnTimerEvent
set aTimer to auto reset
set aTimer enabled = true (Start the timer counting)
console write: Press enter to quit.
console write: App started at.
Wait for console input Return key. -This "pauses" the app.
stop aTimer
dispose aTimer
console write: Terminating

What does "+=" do?

Adds a method call to the event stack.

Is it attaching a method to be called whenever the event happens?

Yes, technically adding it to a list of methods to call when the event happens.

Is this spawned in the same thread as the event

Yes

and can multiple methods be called this way(like doing Elapsed += ArbitrarySecondMethod)

Yes, you could say: Elapsed += FirstThing; Elapsed += SecondThing; etc....

or is this overriding some response/method that is connected to "Elapsed" by default?

No, it's additive.

What would even be the default response?

Nothing, like a button without it's Click even assigned.

In the "OnTimedEvent", how are "source" and the elapsed events actually being passed to it?

Like any delegate, the object that triggered it is sent as the 'sender' along with a new instance of whatever eventargs class the event uses. When you assign a method using += it will check to make sure the method signature matches that patter (object, EventArg of some kind)

I don't see how 'e.SignalTime' even gets past the compiler stage.

Because it's a part of the ElapsedDEventArgs class. Notice the Elapsed at the front of that. It's not a default EventArgs class, but something inheriting from it, with more stuff. That extra stuff is populated by the timer when it fires the event.

How would "OnTimedEvent" even know a Timer object exists?

It doesn't really. It just knows that it is expecting to get both an Object thing and an ElapsedEventArgs thing.

Also, with parameters passed to the "OnTimedEvent", is that (Object x, Args y) a standard format used in this kind of situation

Yes, you'll find most, if not all, .Net event handlers to expect this kind of signature. Always Object sender first and then some kind of EventArg object. That event arg object will change depending on the event it's subscribing to. The MSDN Library should let you see what you'll need.

, what would I look up to learn more about how to use these types of 'add-on' methods(in a general context)

These are simple event methods so anything that talks about .Net events will go over this. For something more specific see:

MS Docs Events

MS Docs Event Patters

MS Docs Events Guide