I'm trying to learn how finalization and destructor works in C#, I tried to run the code in the System.Object.Finalize
example(code copy-pasted, no changes made), but the output is not the same as expected, it shows that the destructor is never called.
The code is:
using System;
using System.Diagnostics;
public class ExampleClass
{
Stopwatch sw;
public ExampleClass()
{
sw = Stopwatch.StartNew();
Console.WriteLine("Instantiated object");
}
public void ShowDuration()
{
Console.WriteLine("This instance of {0} has been in existence for {1}",
this, sw.Elapsed);
}
~ExampleClass()
{
Console.WriteLine("Finalizing object");
sw.Stop();
Console.WriteLine("This instance of {0} has been in existence for {1}",
this, sw.Elapsed);
}
}
public class Demo
{
public static void Main()
{
ExampleClass ex = new ExampleClass();
ex.ShowDuration();
}
}
Update:
When I use visual studio and .net framework 4.5, the code works as expected:
Output same as example:
The example displays output like the following:
Instantiated object
This instance of ExampleClass has been in existence for 00:00:00.0011060
Finalizing object
This instance of ExampleClass has been in existence for 00:00:00.0036294
When I use dotnet core app, the code does not work:
The actual output is:
PS C:wsest> dotnet run
Instantiated object
This instance of ExampleClass has been in existence for 00:00:00.0056874
So why this is different in .NET Core?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…