简体   繁体   中英

Why does the timer Elapsed need += EventHandler?

I'm following this tutorial to write a Windows Service. Every 60 seconds, a new event is raised that writes to the event log. In the code, the new event is raised using the += operator.

// Set up a timer that triggers every minute.
Timer timer = new Timer();
timer.Interval = 60000; // 60 seconds
timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
timer.Start();

Whats the motivation for using this operator here? Why is it not just = ? Especially the + part seems to confuse me..

Elapsed is an event. From ECMA-334 C# Language Specification, chapter 15.8.1 :

The only operations that are permitted on an event by code that is outside the type in which that event is declared, are += and -= .

Just assignment = would be a syntax error here. And this makes sense, because delegates in C# may have many subscribers. From ch.20.1

delegate instance encapsulates an invocation list, which is a list of one or more methods

So there are might be several handlers of Elapsed event, and += is just an appending another one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM