Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

events

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 guarantee that in MyClass I unsibscribe only once even that code is in few methods.
  • Second there are other classes except MyClass witch use OnMyEvent so I don't want to unintentionally unsibscribe from the event in the class.

     MyClass(IModel model)
    {
      _model = model;
      _model.OnMyEvent +=EventHandle;
    }
    Close()
    {
     _model.OnMyEvent -=EventHandle;
    } 
    Disconnect()
    {
     //I want to check if OnMyEvent has already unsibscribed
     //Moreover OnMyEvent is used in other classes and
     //I don't want to mess up with it here 
     _model.OnMyEvent -=EventHandle;
    }
    
like image 839
Arseny Avatar asked Dec 06 '22 20:12

Arseny


1 Answers

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()).

like image 147
Marc Gravell Avatar answered Dec 18 '22 19:12

Marc Gravell