Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In .NET, what happens to a thread when it finishes its task? Do I need to manage this? [duplicate]

Do I need to do something with this thread after it has completed the Console.WriteLine (suspend it or something) or will garbage collection kick in and remove this thread?

public void testThreading() {

    .. do some stuff

    var t = new Thread(() => { Console.WriteLine("hey!"); })
    t.Start();

}
like image 449
anthonybell Avatar asked Oct 22 '13 21:10

anthonybell


1 Answers

Short Answer:

When a thread has finished its process, if nothing else holds a reference to it, the garbage collector will dispose of it automatically.

Long Answer:

After the garbage collector is initialized by the CLR, it allocates a segment of memory to store and manage objects. This memory is called the managed heap, as opposed to a native heap in the operating system. There is a managed heap for each managed process.

All threads in the process allocate memory for objects on the same heap. To reserve memory, the garbage collector calls the Win32 VirtualAlloc function, and reserves one segment of memory at a time for managed applications. The garbage collector also reserves segments as needed, and releases segments back to the operating system (after clearing them of any objects) by calling the Win32 VirtualFree function. The fewer objects allocated on the heap, the less work the garbage collector has to do. When you allocate objects, do not use rounded-up values that exceed your needs, such as allocating an array of 32 bytes when you need only 15 bytes. When a garbage collection is triggered, the garbage collector reclaims the memory that is occupied by dead objects.

The reclaiming process compacts live objects so that they are moved together, and the dead space is removed, thereby making the heap smaller. This ensures that objects that are allocated together stay together on the managed heap, to preserve their locality. The intrusiveness (frequency and duration) of garbage collections is the result of the volume of allocations and the amount of survived memory on the managed heap. The heap can be considered as the accumulation of two heaps: the large object heap and the small object heap. The large object heap contains very large objects that are 85,000 bytes and larger. The objects on the large object heap are usually arrays. It is rare for an instance object to be extremely large.

Reference

Fundamentals of garbage collection

like image 134
Anthony Russell Avatar answered Oct 01 '22 12:10

Anthony Russell