The impact of finalizer threads on the life cycle of an object

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.