[MessagingCenter] Do I need to unsubscribe? When to unsubscribe?

If I subscribe in a class Contructor, e.g. in DataManager Constructor I wrote "subscribe App.onResume", when do I unsubscribe it?

In iOS, you usually addObserver in ViewDidLoad / Init method, then you could removeObserver in dealloc. What's the equivalence in Xamarin? I've seen a few Open Source Apps like BikeSharing360, they only subscribe in constructor, but without unsubscribe it.

My concerns are if I don't unsubscribe it from DataManager, can DataManager gets released? If it can be released, then will that cause exceptions as it still subscribes App.onResume.

Answers

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    OnDisappearing should be a good position to Unsubscribe

  • NMackayNMackay GBInsider, University mod
  • RayQuRayQu NZMember

    @AlessandroCaliaro @NMackay

    Thx for replying. But in above example, I've tried to write a subscribe in a utility class, DataManager, there is no OnDisappearing or Popped.

    I've written the subscribe in the Constructor method, but I have no idea when I should unsubscribe it as C# doesn't provide a destructor.

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    @RayQu you should unsubscribe when you don't want to receive messages. If you want to receive messages during all the application life, you should subscribe in "OnStart" and unsubscribe in "OnSleep".

  • markosmarkos Member

    C# does have finalizers, although I've never seen them used anywhere..

    class Car
    {
        ~Car()  // finalizer
        {
            // cleanup statements...
        }
    }
    
  • JohnHardmanJohnHardman GBUniversity mod

    @markos said:
    C# does have finalizers, although I've never seen them used anywhere..

    class Car
    {
        ~Car()  // finalizer
        {
            // cleanup statements...
        }
    }
    

    Specifying finalizers in C# results in more work for the garbage collector. If you want performant code, it's best to avoid finalizers.

    Also, note that Xamarin.Forms itself is currently inconsistent about how it implements the dispose pattern and what it does regarding finalizers. If you add a finalizer to a custom renderer, most (but not all) of the time it will never be called.

    Whilst destructors were the place to do cleanup in C++, finalizers are far from an ideal place to do cleanup in C#.

Sign In or Register to comment.