alchemical
alchemical

Reputation: 13985

When to use custom c# events

When is it appropriate to raise an event in C#?

As an example, in our system we have data objects being sent to us, say 50 per minute, from an external system. Upon receiving a data packet, we need to have it processed by another object. Would an event or a simple method call be better to use in this situation?

An event seems like a natural fit intuitively, but I'm not clear as to what advantage this may offer as compared to simply using a regular method call.

Upvotes: 0

Views: 425

Answers (3)

Abhijeet Patel
Abhijeet Patel

Reputation: 6878

IMO using a Queue would be an appropriate first step. Code processing the Queue can in turn either raise events or accept a delegate which performs different tasks based on the kind of data object. Action or Func should work well here.

Remember that when you use events, you have to ensure that handlers get unregistered in a timely manner or else you could have leaks.

Upvotes: 1

Rex M
Rex M

Reputation: 144122

Events should be used when it is inappropriate for the code which originates the action to have direct knowledge of the code(s) which react to that action.

On one hand, an event does sound appropriate here, because the code which handles data reception should not be dependent on the implementation of the code which does something with said data. Otherwise the data reception code is now responsible for two things - receiving the data and delegating the processing of it.

On the other hand, if the particular processing of the data is directly tied to act of it being sent by the external caller, it may make more sense to make it a function call. We don't really have enough information in your question to say for sure.

Upvotes: 4

James Black
James Black

Reputation: 41858

In this case an event doesn't make sense. Events tend to be to inform about what is going on, not to replace function calls. They are more informative.

So, you may want to pass in an Action<> function, so that you can then call the function that was passed in, to do the processing.

This would be better than a function call, IMO.

You can look at this page for an example: http://www.claassen.net/geek/blog/2007/12/action-func-never-write-another.html

Update: If you are not using C#3 then you may want to use a delegate instead, which, an event handler is a specialized delegate.

Upvotes: 0

Related Questions