Avoid duplicate event subscriptions in C#

前端 未结 5 1961
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-25 15:28

How would you suggest the best way of avoiding duplicate event subscriptions? if this line of code executes in two places, the event will get ran twice. I\'m trying to avoid

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-25 16:01

    I use your approach except one detail. I think, that events should be subscribed when you create new instance of subscriber or theObject, this makes code more straight. Thus, all you need is just carefully watch after correct objects disposing (dispose patten is convenient solution for this).

    You mentioned that you use 3rd party event, that means that you can't provide your own realisation for add/remove methods, as you have been advised. But in your own classes with your own events you should define your own realisation of add/remove methods for event in order to solve your problem.

提交回复
热议问题