简体   繁体   中英

Do I use a delegate or an event

I have a Connection class which reads packets (commands) from a text stream and then distributes the commands to a set of handlers which process the commands as they see fit.

Eg.. Connection class reads in a command "HELLO" and then passes the command off to the handlers, where one or more handler may do something useful with the HELLO command.

Right now I use a delegate called HandleCommand which all command handlers must adhere to in order to receive the commands.

The question is, would it be more logical to use an event (eg.. CommandReceived) which the handlers could individually subscribe to? I'm having a hard time weighing up the pros and cons. it seems more wasteful to make it an event, because then an EventArgs class has to be generated for each command received.

In contrast, there is also a DisconnectCallback delegate which I strongly believe would be better as an event and will probably change.

Thank you

It seems your distributor now has to keep a list of handlers (class or delegates). That means you are duplicating the functionality of event .

The situation seems to call for events. It would decouple the components.

Concerning the 'wastefulness' of events and eventargs, see this question and stop worrying.

First - until you have evidence that it's a performance bottleneck, don't sacrifice clarity. The GC is fast and it's unlikely cleaning up a short-lived eventargs class will be the dominating performance factor here.

Anyway, If the consumers are only going to read and not modify the data, I'd make it an event. Otherwise you'd probably want to make an interface for a 'filter' that can read and modify, and pass the new value to the next one.

Events would be the most obvious approach as there are more than one command handlers.

I'm curious as to how command handlers "adhere" to a connection using delegates. You have to either simulate the event behavior by using a list of listeners or the command must actively call the handlers, what indeed compromises decoupling.

You are not required to use EventHandler or EventHandler<T> when creating an event, even though that is against Microsoft's recomendation. You can use your current delegate as the datatype for the event like so:

public event MyDelegateType EventName;

Edit: If you are concerned about performance you can use an EventHandlerList class like so:

private EventHandlerList _events = new EventHandlerList();
private static object MyDelegateKey = new object()
public event MyDelegate EventName {
  add {
     _events.AddHandler(MyDelegateKey, value);
  }
  remove {
     _events.RemoveHandler(MyDelegateKey, value);
  }
}

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