Which C# pattern has better performance to avoid duplicated event handlers?

前端 未结 4 786
你的背包
你的背包 2021-02-14 03:54

There are basically two patterns in avoiding duplicated registering of event handlers: (According to this discussion: C# pattern to prevent an event handler hooked twice)

<
4条回答
  •  执笔经年
    2021-02-14 04:28

    1. won't work for external callers, and is not very efficient anyway
    2. should be fine (note that it creates 2 delegate instances each time, though), however also consider
    3. in most scenarios, it should be easy to know whether you are already subscribed; if you can't know, then that suggests an architectural problem

    The typical usage would be "subscribe {some usage} [unsubscribe]" where the unsubscribe may not be necessary, depending on the relative lifetimes of the event publisher and subscriber; if you actually have a re-entrant scenario, then "subscribe if not already subscribed" is itself problematic, because when unsubscribing later, you don't know if you're preventing an outer iteration receiving the event.

提交回复
热议问题