Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What prevents a Thread in C# from being Collected?

In .NET, after this code, what mechanism stops the Thread object from being garbage collected?

new Thread(Foo).Start();
GC.Collect();

Yes, it's safe to assume something has a reference to the thread, I was just wandering what exactly. For some reason Reflector doesn't show me System.Threading, so I can't dig it myself (I know MS released the source code for the .NET framework, I just don't have it handy).

like image 708
ripper234 Avatar asked Sep 17 '08 10:09

ripper234


People also ask

Does C support thread?

C does not contain any built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature. This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C program using POSIX.

What is not thread safe in C?

These extended mathlib functions use a global variable, _signgam , so are not thread-safe. The C89 multibyte conversion functions (defined in stdlib. h ) are not thread-safe, for example mblen() and mbtowc() , because they contain internal static state that is shared between all threads without locking.

Can a thread terminate a process?

A thread can also explicitly terminate itself or terminate any other thread in the process, using a mechanism called cancelation. Because all threads share the same data space, a thread must perform cleanup operations at termination time; the threads library provides cleanup handlers for this purpose.

Does a thread automatically be killed?

A thread is automatically destroyed when the run() method has completed. But it might be required to kill/stop a thread before it has completed its life cycle. Previously, methods suspend(), resume() and stop() were used to manage the execution of threads.


2 Answers

The runtime keeps a reference to the thread as long as it is running. The GC wont collect it as long as anyone still keeps that reference.

like image 151
EricSchaefer Avatar answered Sep 16 '22 22:09

EricSchaefer


It depends on whether the thread is running or not. If you just created Thread object and didn't start it, it is an ordinary managed object, i.e. eligible for GC. As soon as you start thread, or when you obtain Thread object for already running thread (GetCurrentThread) it is a bit different. The "exposed object", managed Thread, is now hold on strong reference within CLR, so you always get the same instance. When thread terminates, this strong reference is released, and the managed object will be collected as soon as you don't have any other references to (now dead) Thread.

like image 27
Ilya Ryzhenkov Avatar answered Sep 20 '22 22:09

Ilya Ryzhenkov