Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a blank Winform with a destructor method

public partial class Form1 : Form
{
    public Form1()
    {
        System.Diagnostics.Trace.WriteLine("Form1.Initialize " + this.GetHashCode().ToString());
        InitializeComponent();
    }
    ~Form1()
    {
        System.Diagnostics.Trace.WriteLine("Form1.Dispose " + this.GetHashCode().ToString());
    }
}

When the form is destroyed, I want it to write to the output window:

(Form1 opened)
Form1.Initialize 41149443
(Form1 closed)
Form1.Dispose 41149443

MSDN suggests 3 ways in implementing destructor:

However, none of these ways write "Form1.Dispose 41149443" to the output Window. Therefore, I am not able to tell whether the form has been destroyed or not. Suggestions ?

Should I give up hope on achieving this due to uncertainty of garbage collector?

Is there another way to know whether Form1 has been garbage collected ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
312 views
Welcome To Ask or Share your Answers For Others

1 Answer

Only one of the three ways to implement a destructor that you list actually involves a destructor, and that's ~Destructor().

If you implement IDisposable, and dispose of your object, then the code in Dispose will run, but there's no reason to think that your destructor will.

I think you chasing the impossible here. Destructors run as and when the garbage collector so decrees. It's not something that you have any control over. The GC is well within its rights to form the opinion that running destructors simply wastes time, and if there is plenty of memory it will form that opinion.

If you need predictable disposal, finalization etc., then use IDisposable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...