How is garbage collection going for classes that have static methods in C # / VB.NET?

Does the object set the null object to MARKED for the GC?

EDIT: the class has several static methods. when using these methods in your program, what is the best way to ensure that objects are marked to the GC after a certain point?

+6
garbage-collection c #
source share
4 answers

Methods are not garbage collection at all, so itโ€™s not entirely clear what your question means.

Similarly, you never set an object to null. You can make the value of the variable null, but it does not mean anything for any object that the variable previously spoke about. It just means that the next time the garbage collector searches for a living object, this variable will not add any object to the set of objects that should be stored at the end of the GC.

I suggest you read the article Jeffrey Richter's article on garbage collection for more information, and then ask any additional specific questions when you have the basics.

+11
source share

If you ask what happens to objects referenced by variables in static methods, then these objects become available for garbage collection when they are no longer in scope.

If you are talking about objects referenced by static fields, then they will not be collected in simple words until the links are set to zero.

The following example may illustrate this better:

class Example { private static object field1 = new object(); public static void SomeMethod() { object variable1 = new object(); // ... } public static void Deref() { field1 = null; } } 

The object referenced by field1 will be created when the class is loaded and remains root, even if the objects of the Example class are created and destroyed. The only way to collect this object garbage is to call the Deref () method, which will dereference it by setting a reference to null. (In fact, you can unload classes by unloading the application domain, but this is somewhat more advanced, and not that you probably often come across this.)

Conversely, the static SomeMethod () method creates an object and refers to it with variable1. This object is intelligent for garbage collection as soon as it goes beyond the scope (at the end of the method). As a rule, it could be assembled earlier if the rest of the method does not refer to it.

+4
source share

objects are not marked for GC, they are marked (by the presence of a variable that refers to or points to them), NOT to be collected by Garbage. When every variable or object reference in all running threads and in all global static variables and in all registers cpu was deleted, went out of scope or set to zero, then the object is no longer available and GC will collect it.

+3
source share

Think of static methods as class methods. They are available regardless of whether or not the object exists. They do not affect garbage collection.

0
source share