Why the page's destructor never called?

aluzi liu 486 Reputation points
2022-09-11T09:30:31.997+00:00

[Xamain.Forms Android]
I create a blank page,add destructor like this:

        ~EmptyPage()  
        {  
            Console.WriteLine("Empty page destructor running..............");  
        }  
  

And then I use:

                var page0 = new EmptyPage();  
                await Shell.Current.Navigation.PushAsync(page0);  
  

to open the page, and I manully close the page, I hope console will output "Empty page destructor running..............“, but nothing.
It seemd that the destructor never called, why?

My real question is, I am using "MessagingCenter.Subscribe" in the EmptyPage, and I found after close the page, the MessagingCenter still working in memory, it will cause memory leak, right?
I want to Unsubscribe in the destructor, but destructor never called, so what is the best way to Unsubscribe?
I try "OnDisappearing" event, but if I open new page on EmptyPage, it will rise OnDisappearing on EmptyPage, that was not I wanted...
I want Unsubscribe only when EmptyPage is closed, any suggestion?

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,542 questions
0 comments No comments
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 43,371 Reputation points Microsoft Vendor
    2022-09-12T06:11:00.887+00:00

    Hello,

    You could refer to this official documentation Finalizers (C# Programming Guide), and find the following contents:

    Finalizers cannot be defined in structs. They are only used with classes.
    A class can only have one finalizer.
    Finalizers cannot be inherited or overloaded.
    Finalizers cannot be called. They are invoked automatically.
    A finalizer does not take modifiers or have parameters.

    In MAUI, it is more recommended to use BackButtonBehavior to unsubscribe the MessagingCenter.

    You could refer to the following code:

    In EmptyPage.xaml:

       <Shell.BackButtonBehavior>   
           <BackButtonBehavior Command="{Binding TestCommand}"/>  
       </Shell.BackButtonBehavior>  
    

    In your ViewModel.cs:

       TestCommand = new Command(Unsubscribe); // the Unsubscribe method is your own method to unsubscribe MessagingCenter  
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.