What's a proper way to unsibscribe from events in c#?

后端 未结 4 661
Happy的楠姐
Happy的楠姐 2021-01-13 18:09

I have a model class with an event which I subscribe from other classes. I want to subscribe and un-subscribe in each class correctly.

  • First I want to guarant
4条回答
  •  春和景丽
    2021-01-13 19:01

    If you only subscribe once, it doesn't matter how many times you unsubscribe - unsubscribing when you don't have a subscription is a no-op. Equally, the entire point of the event API is that you can't accidentally unsubscribe other subscriptions (either other types, or other instances of the same type).

    As such, the code as shown should be fine, although it might be worth moving the two calls to a single method that handles this. That might be overkill, though.

    Also, if your type is IDisposable, make sure it gets called in that code-path too (presumably by calling Close()).

提交回复
热议问题