The topic of this blog is a bit heavy, so let's talk about the sang sang tightly of. NET objects. First, we have to define life and death. In this blog, whenever you talk about an object that is dead, it means that the user can no longer obtain its reference. This definition is a user-friendly definition, because there are many times when objects remain on the managed heap, and the CLR can still get it by some means (such as through SYNCBLK in the RCW cache), but the state of being "alive or dead" is not within the scope of today's discussion.
Anyway Known. NET rely on GC to manage objects that are assigned to the managed heap (that is, the new stuff). To provide functionality similar to the destructor in C + +, that is, when an object is about to die, a piece of user code is executed to do some cleanup work, such as raising the release method on a COM component.
For performance reasons, the CLR uses a separate thread to execute the object's Finalize method, so the execution of the Finalize method is not part of the gc.collect. The following program validates this assertion.
using System;
using System.Threading;
class ObjectWithFinalizer
{
~ObjectWithFinalizer()
{
Thread.Sleep(1000);
Console.WriteLine("Finalize in thread {0}", Thread.CurrentThread.ManagedThreadId);
}
}
class Program
{
public static void Main()
{
Console.WriteLine("Run in thread {0}", Thread.CurrentThread.ManagedThreadId);
ObjectWithFinalizer owf = new ObjectWithFinalizer();
GC.Collect();
Console.WriteLine("GC.Collect() end");
}
}
The result of the program running is
Run in thread 1
GC.Collect() end
Finalize in thread 2