views:

187

answers:

3

Maybe this is a dumb question, but do event listeners use CPU cycles like a timer, or are they inactive until the event is fired?

Is it language specific, or do all languages handle this basically the same?

I want to write a tiny service that only does anything when a network disconnect event is fired, and I don't want the service to use up resources just listening (other than memory of course).

I plan to do something like this

using NetworkUtilities;
    ManagementEventWatcher networkAdapterArrivalWatcher = new ManagementEventWatcher("\\root\\wmi","SELECT * FROM MSNdis_NotifyAdapterArrival ");
              networkAdapterArrivalWatcher.Options.Timeout = new TimeSpan(0,0,5);

    ManagementEventWatcher networkAdapterRemovalWatcher = new ManagementEventWatcher("\\root\\wmi","SELECT * FROM MSNdis_NotifyAdapterRemoval " );
              networkAdapterRemovalWatcher.Options.Timeout = new TimeSpan(0,0,5);

    ConnectionNotifierHandler handler = new ConnectionNotifierHandler();
              networkAdapterArrivalWatcher.EventArrived += new EventArrivedEventHandler(handler.Arrived);
              networkAdapterRemovalWatcher.EventArrived += new EventArrivedEventHandler(handler.Removed);

    //Start watching for events
    networkAdapterArrivalWatcher.Start();
    networkAdapterRemovalWatcher.Start();

    public void Arrived(object sender, EventArrivedEventArgs e)
    {
            using (ManagementBaseObject ev = e.NewEvent)
            {
             //Log the event
            }
    }

    public void Removed(object sender, EventArrivedEventArgs e)
    {
            using (ManagementBaseObject ev = e.NewEvent)
            {
             //Log the event
            }   
    }
A: 

Event Listeners don't use any CPU time until the event is actually fired (and your Event Handler is called).

There's no background process involved with an Event Listener.

Justin Niessner
+1  A: 

In C#, events are merely function delegates (pointer to function), which will be called "on demand" and won't use any extra CPU cycle.

BUT, if you are referring to monitoring events like:

  • OnConnecitonPending for some socket listener.
  • OnWindowMessage for a window application.

I think those sure use a thread to monitor their events and of course will cost extra CPU.

Eran Betzalel
A: 

Generally, event listeners conforming to a built in event-listening system don't use CPU time until the event is fired. Rather, they are delegates that are triggered by the event. Their interest in the event is noted by the system. This is most obvious, for example, with Objective-C/Cocoa style delegates, but the principle applies just about everywhere.

phoebus