Detecting event subscriptions

  • Thread starter Thread starter kirk
  • Start date Start date
K

kirk

I have a class with a native API inside. The API, when called,
determines the state of some entity.

I'd like to setup the interface to this class to have an event that
can be subscribed to, called OnStateChange, for example. When
subscribed to, I envisioned a timer would turn on and start calling
the API continuously every X amount of seconds and if a change
occurred, the event would fire.

My question is, what is the best way to implement code to flip the
timer for calling the API on and off? I know I can use a separate
timer that kicks in when the class is instantiated, that can
continually test the OnStateChange event for null, but this seems like
overkill. Any ideas?

Thanks.
 
[...]
My question is, what is the best way to implement code to flip the
timer for calling the API on and off? I know I can use a separate
timer that kicks in when the class is instantiated, that can
continually test the OnStateChange event for null, but this seems like
overkill. Any ideas?

Sure. Just write your own explicit event.

When you use the "event" keyword, the compiler automatically generates the
add and remove methods for you. But you can write those yourself if you
like. Then, in the add you can enable a timer, and in the remove you can
see if the delegate reference is null after doing the removal and disable
the timer if it is.

Jon Skeet's article on events includes some examples of explicit event
implementations:
http://www.yoda.arachsys.com/csharp/events.html

This MSDN article isn't about explicit event implementations per se, but
since it deals with a situation in which you must explicitly implement an
event, it winds up being an example of that anyway:
http://msdn2.microsoft.com/en-us/library/ak9w5846(VS.80).aspx

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top