Should be an easy one. Let's say I have the following code:
void Method()
{
AnotherMethod(new MyClass());
}
void AnotherMethod(MyClass obj)
{
Console.WriteLine(obj.ToString());
}
If I call "Method()", what happens to the MyClass object that was created in the process? Does it still exist in the stack after the call, even though nothing is using it? Or does it get removed immediately?
Do I have to set it to null to get GC to notice it quicker?
After the call to Method completes, your MyClass object is alive but there are no references to it from a rooted value. So it will live until the next time the GC runs where it will be collected and the memory reclaimed.
There is really nothing you can do to speed up this process other than to force a GC. However this is likely a bad idea. The GC is designed to clean up such objects and any attempt you make to make it faster will likely result in it being slower overall. You'll also find that a GC, while correctly cleaning up managed objects, may not actually reduce the memory in your system. This is because the GC keeps it around for future use. It's a very complex system that's typically best left to it's own devices.
If I call "Method()", what happens to the MyClass object that was created in the process?
It gets created on the GC heap. Then a reference to its location in the heap is placed on the stack. Then the call to AnotherMethod happens. Then the object's ToString method is called and the result is printed out. Then AnotherMethod returns.
Does it still exist in the stack after the call, even though nothing is using it?
Your question is ambiguous. By "the call" do you mean the call to Method, or AnotherMethod? It makes a difference because at this point, whether the heap memory is a candidate for garbage collection depends upon whether you compiled with optimizations turned on or off. I'm going to slightly change your program to illustrate the difference. Suppose you had:
void Method()
{
AnotherMethod(new MyClass());
Console.WriteLine("Hello world");
}
With optimizations off, we sometimes actually generate code that would be like this:
void Method()
{
var temp = new MyClass();
AnotherMethod(temp);
Console.WriteLine("Hello world");
}
In the unoptimized version, the runtime will actually choose to treat the object as not-collectable until Method returns, after the WriteLine. In the optimized version, the runtime can choose to treat the object as collectible as soon as AnotherMethod returns, before the WriteLine.
The reason for the difference is because making object lifetime more predictable during debugging sessions often helps people understand their programs.
Or does it get removed immediately?
Nothing gets collected immediately; the garbage collector runs when it feels like it ought to run. If you need some resource like a file handle to be cleaned up immediately when you're done with it then use a "using" block. If not, then let the garbage collector decide when to collect memory.
Do I have to set it to null to get GC to notice it quicker?
Do you have to set what to null? What variable did you have in mind?
Regardless, you do not have to do anything to make the garbage collector work. It runs on its own just fine without prompting from you.
I think you're overthinking this problem. Let the garbage collector do its thing and don't stress about it. If you're having a real-world problem with memory not being collected in a timely manner, then show us some code that illustrates that problem; otherwise, just relax and learn to love automatic storage reclamation.
Actually, the instance will be declared on the heap, but have a look at Eric Lipper's article, The Stack is an Implementation Detail.
In any case, because there will be no more references to the instance after the function executes, it will be (or, more accurately, can be) deleted by the garbage collector at some undefined point in the future. As to exactly when that happens, it's undefined, but you also (essentially) don't need to worry about it; the GC has complicated algorithms that help it determine what and when to collect.
Does it still exist in the stack after the call
Semantics are important here. You asked if it still exists on the stack after the method call. The answer there is "no". It was removed from the stack. But that's not the final story. The object does still exist, it's just no longer rooted. It won't be destroyed or collected until the GC runs. But at this point it's no longer your concern. The GC is much better at deciding when to collect something than you or I are.
Do I have to set it to null to get GC to notice it quicker?
There's almost never a good reason to do that, anyway. The only time that helps is if you have a very long running method and an object that you are done with early that otherwise won't go out of scope until the end of the method. Even then, setting it to null will only help in the rare case where the GC decides to run during the method. But in that case you're probably doing something else wrong as well.
In C# the new MyClass() is scoped only to live inside Method() while it is active. Once that AnotherMethod() is finished executing, it is out of scope and gets unrooted. It then remains on the heap until the GC runs its collection cycle and identifies it as an unreferenced memory block. So it is still "alive" on the heap but it is inaccessible.
The GC keeps track of what objects can possibly still be referenced later in the code. It then, at intervals, checks to see if there are any objects still alive that could not possibly be referenced later in the code, and cleans them up.
The mechanics of this are somewhat complex, and when these collections will happen depends on a variety of factors. The GC is designed to do these collections at the most optimal time (that it can establish) and so, while it is possible to force it to do a collection, it is almost always a bad idea.
Setting the variable to null will have very little overall effect on how soon the object is dealt with. While it can, in some small corner cases, be of benefit it is not worth littering your code with redundant assignments which will not affect your codes performance and only harm readability.
The GC is designed to be as effective as possible without you needing to think about it. To be honest, the only thing you really need to be mindful of is being careful when allocating really large objects that will stay alive for a long time, and that's generally quite rare in my experience.
As far as I know, the object is only valid inside your method context. After the method "Method()" is executed it is added to the dispose queue.
Related
I got this idea while thinking of ways to recycling objects. I am doing this as an experiment to see how memory pooling works and I realize that in 99% of scenario this is very unnecessary .
However, I have a question. Is there a way to force the GC to keep the object? In other words, can I tell the GC not to destroy an object and say instead have new reference created in a list that holds available to use objects? The issue, though I have not tested this, is that if I add something like this to a list:
~myObject()
{
((List<myObject>)HttpContext.Current.Items[typeof(T).ToString()]).add(this);//Lets assume this is ASP
}
it will add a pointer to this object into the list, but if the object is destroyed I will get a null pointer exception because the object is no longer there. However, maybe I could tell the GC not to collect this item and thus keeping the object?
I know this is the type of stuff that most programmers would go "why the hell would you do this?". But on the other hand programming is about trying new and learning new things. Any suggestions, thoughts, implementatons? Any help would be greatly appreciated!
Yes, this is legitimate. It is called 'resurrection'. When you assign the this reference to somewhere that is 'live', then the object is no longer considered garbage.
You will also need to reregister for finalization using GC.ReRegisterForFinalize(this), or the next time the object becomes garbage, it will not be finalized (the destructor will not be called).
You can read more about object resurrection in this MSDN Magazine article.
Yes, this is possible and it even has a name: resurrection.
but if the object is destroyed I will get a null pointer exception because the object is no longer there.
Much worse, you would get an invalid pointer (reference) error. And possibly a blue screen or crashing server. But luckily the CLR won't let that happen. Simply putting a doomed instance in any kind of list makes it reachable again and then it will not be reclaimed.
When you want your object to be recycled multiple times you will have to call GC.ReRegisterForFinalize(x) on it.
Most practical answer though: don't do it. The destructor alone accounts for considerable overhead and there are many ways to get this wrong.
The GC is only going to take care of objects whose reference is gone whether by going out of scope of being explicitly released.
Either way you will want to look at the KeepAlive and SuppressFinalize methods to prevent GC from garbage collecting your objects. Once you are truly done with them you'll need to register them to be picked up by the collector using ReRegisterForFinalize.
Scenario
Lets say that I've decided I really need to call GC.Collect();
What do I need to do to ensure that an object is prepared to be garbage collected appropriately before I actually call this method?
Would assigning null to all properties of the object be enough? Or just assigning null to the object itself?
If you really need to know why.....
I have a distributed application in WCF that sends a DataContract over the wire every few seconds, containing 8 Dictionaries as DataMembers.
This is a lot of data and when it comes into the Client-side interface, a whole new DataContract object is created and the memory usage of the application is growing so big that I'm getting OutOfMemory Exceptions.
Thanks
EDIT
Thanks for all the comments and answers, it seems that everyone shares the same opinion.
What I cannot understand is how I can possibly dispose correctly because the connection is open constantly.
Once I've copied the data over from the incoming object, I don't need the object anymore, so would simply implementing IDisposable on that DataContract object be enough?
My original problem is here - Distributed OutOfMemory Exceptions
As long as nothing else can see the object it is already eligible for collection; nothing more is required. The key point here is to ensure that nothing else is watching it (or at least, nothing with a longer lifetime):
is it in a field somewhere?
is it in a variable in a method that is incomplete? (an infinite loop or iterator block, perhaps)
is it in a collection somewhere?
has it subscribed to some event?
it is captured in a closure (lambda / anon-method) that is still alive?
I genuinely doubt that GC.Collect() is the answer here; if it was eligible it would have already been collected. If it isn't elgible, calling GC.Collect() certainly won't help and quite possibly will make things worse (by tying up CPU when nothing useful can be collected).
You don't generally need to do anything.
If the object is no longer referenced then it's a candidate for collection. (And, conversely, if the object is still referenced then it's not a candidate for collection, however you "prepare" it.)
You need to clean up any unmanaged resources like database connections etc.
Typically by implementing IDisposable and call Dispose.
If you have a finalizer you should call GC.SuppressFinilize.
The rest is cleaned up by the garbage collector.
Edit:
And, oh, naturally you need to release all references to your object.
But, and here is this big but. Unless you have a very very special case you don't need to call GC.Collect. You probably forgets to release some resources or references, and GC.Collect won't help you with that. Make sure you call Dispose on everything Disposable (preferably with the using-pattern).
You should probably pick up a memory profiler like Ants memory profiler and look where all your memory has gone.
If you have no more direct reference to an object, and you're running out of memory, GC should do this automatically. Do make sure you call .Dispose() on your datacontext.
Calling GC.Collect will hardly ever prevent you from getting OutOfMemory exceptions, because .NET will call GC.Collect itself when it is unable to create a new object due to OOM. There is only one scenario where I can think of and that is when you have unreferenced objects that are registered in the finalizable queue. When these objects reference many other objects it can cause a OOM. The solution to this problem is actually not to call GC.Collect but to ensure that those objects are disposed correctly (and implement the dispose pattern correctly when you created those objects).
Using GC.Collect in general
Since you are trying to get rid of a very large collection, it's totally valid to use GC.Collect(). From the Microsoft docs:
... since your application knows more about its behavior than the runtime does, you could help matters by explicitly forcing some collections. For example, it might make sense for your application to force a full collection of all generations after the user saves his data file.
"Preparing" your objects
From the excellent Performance Considerations for Run-Time Technologies in the .NET Framework (from MSDN):
If you keep a pointer to a resource around, the GC has no way of knowing if you intend to use it in the future. What this means is that all of the rules you've used in native code for explicitly freeing objects still apply, but most of the time the GC will handle everything for you.
So, to ensure it's ready for GC, Make sure that you have no references to the objects you wish to collect (e.g. in collections, events, etc...). Setting the variable to null will mean it's ready for collection before the variable goes out of scope.
Also any object which implements IDisposable should have it's Dispose() method called to clean up unmanaged resources.
Before you use GC.Collect
Since it looks like your application is a server, using the Server GC may resolve your issue. It will likely run more often and be more performant in a multi-processor scenario.
The server GC is designed for maximum throughput, and scales with very high performance.
See the Choosing Which Garbage Collector to Use within Performance Considerations for Run-Time Technologies in the .NET Framework (from MSDN):
SO I already know about memory management in objective C, and I never had to know about it while programming in .net (C#). But i still have some questions about how everything is done.
-Why does the code leak in objective c if we allocate an object and not release it?
-Why doesn't this leak in C#?
-What are some advantages and disadvantages of automatic-garbage-collecting?
-Why not use autorelease on every allocated object (Objective C)?
-Is it possible to take care of the memory manually (C#)? so let's say i instantiate an object, and when I'm done i want to release it, and i don't want to wait for the garbage collector to do it?
It leaks in Objective-C because Objective-C doesn’t take any action on it. It relies on you doing all the work. It doesn’t leak in C# (more precisely, in .NET) because it employs a garbage collector which cleans up objects that are no longer used.
The main advantage of garbage collection is the above: you have far fewer memory leaks. (It’s still possible to have a memory leak, e.g. by filling a list indefinitely, but that’s harder to do accidentally.) It used to be thought that garbage collection has a disadvantage in that it could slow down the program because it keeps doing the garbage collection in the background and you have little control over it. In reality, however, the difference is negligible: there are other background tasks on your computer (e.g. device drivers) running all the time, the garbage collector doesn’t break the camel’s back either.
Auto-deallocation (as it is employed in C++ when a non-pointer variable goes out of scope) is dangerous because it opens the possibility to have a reference to it still in existence even after the object has been disposed. If your code then tries to access the object, the process goes kaboom big time.
Yes, it is possible to tell C# to release memory by invoking the garbage collector directly (GC.Collect()). However, I have yet to see a case where this is at all necessary. If you actually run out of memory, the garbage collector will already kick in automatically and free as much as it can.
Objective-C isn't a garbage-collected language, so it has no way of knowing that an object won't be used anymore unless you tell it. That's the purpose of the .NET garbage collector: it checks to see which objects can no longer be used by the program, and- at some point- gets rid of them to free up memory. There are no guarantees as to when, or if, it will ever free any given abandoned object; it's just trying to keep memory usage from going out of control.
C# can't release an object without the garbage collector. If you release an object that's still being referenced, your program is going to crash when you try to use that. Which is always the risk of manual memory management, but like all "memory-managed languages", it is trying to prevent you from making exactly that mistake. If you want to explicitly shut down an object's operation, implement the interface IDisposable for that object's type, and use the Dispose() method on that object- essentially a destructor. Be sure you're done with it, of course, and that the object will behave correctly (by throwing exceptions) if something tries to use it after it's been Dispose()d of.
Objective-C is reference-counted. When an object is out of references, it deletes itself. It's not a bad solution to the "is someone still using this object?" problem, except for data structures that refer to themselves; circular data structures will hang around forever unless carefully handled. .NET isn't a reference counter, so it will get rid of circular data structures that can't be reached from running code.
Autorelease is just a "release later", for returning a value that should self-destruct if the code that grabs it doesn't immediately want to hold onto it, as far as I understand. (I'm not an Objective-C programmer, though.) It gets around the "who releases this object?" problem for calls that return an object, without destroying it before the function is finished. It's a special use case, though, and it doesn't make sense in most other cases.
The advantage of automatic garbage collection is that you do not have to explicitly free/release your objects as you said. The disadvantage is you cannot be sure when (or even if) any given object instance will be released.
C# has other mechanisms to release other resources like files, or db connections that have to be released detirminitely. For example, using allows you to make sure that IDispose is called on an object for sure.
Garbage collected systems tend to have more memory in use at any given time than a well tuned manual implementation. Of course, you do not have memory leaks.
The quality and performance of garbage collectors can vary quite a bit which is something you may not have a lot of control over. For example, there may be a noticable lag when the GC runs. In .NET, you can call GC.Collect() to tell the GC that now would be a good time but it may or may not listen.
These days Objective-C is also garbage collected on the Mac. On the iPhone it is reference counted though so I assume that is where you are running into the issue.
On garbage collected systems, you can still run into the issue where a an object hangs onto a reference to an object that you would expect to be garbage collected. The garbage collector will not clean-up this up and so the memory is essentially leaked.
In reference counted systems, you do not have to keep track of every object that points at your object instances but you do have to specify that you want them released.
EDIT: I guess I did not say this explicitly - you cannot manually control memory allocation in C#.
This may likely be an issue with my inexperience using a Managed Language. The issue essentially is a loop within an objects method, which executes over about 20 seconds, throughout the duration of this loop the programs overall memory usage constantly goes up. Now all the variables within the loop which are modified are variables defined within the loops scope (ie. no class members are changed/re-allocated within the loop). After the entire method completes the excess memory is still being used.
I have absolutely no idea why/where this issue is but here are some things which may be a factor:
I use fonts within the loop, but I '.Dispose()' of them and have verified that there is no GDI leak.
I have try/catch statements which are in active use.
Objects are allocated...
So again, any ideas on where this issue may be coming from would be very helpful, I would post code but there is a lot of it. Also as mentioned above the memory is not cleaned up after the method call is done, and even after the object on which the method was invoked has gone out of scope.
Edit
I also just tried the GC.Collect() method, and nothing has changed in the overall result. I have no idea, but does this mean that the memory is not considered 'Garbage'? Again all the allocation is done within the scope of the loop so shouldn't it be considered garbage after the loop terminates. I understand the GC won't immediately get to cleaning it up, but using the GC.Collect() call should force that?
.NET uses traced garbage collection instead of the classic reference counting mechanism.
As soon as your .NET code releases an object or data, it doesn't get cleaned up instantly. It sits around for a while before being cleaned up. The garbage collector is a separate entity wandering around.
Microsoft states about the garbage collector
However, memory is not infinite.
Eventually the garbage collector must
perform a collection in order to free
some memory.
The garbage collector will come around at its own leisure based on complex algorithms. It will eventually clean everything up, if not at the end of the program lifetime. It's not recommended we poke or prod the garbage collector through System.GC members because we're supposed to assume it knows best.
Garbage collector will release objects if there is no pointer pointing to them. Be sure you don't keep not necessary objects in your variables (especially in arrays).
In my experience it seems that most people will tell you that it is unwise to force a garbage collection but in some cases where you are working with large objects that don't always get collected in the 0 generation but where memory is an issue, is it ok to force the collect? Is there a best practice out there for doing so?
The best practise is to not force a garbage collection.
According to MSDN:
"It is possible to force garbage
collection by calling Collect, but
most of the time, this should be
avoided because it may create
performance issues. "
However, if you can reliably test your code to confirm that calling Collect() won't have a negative impact then go ahead...
Just try to make sure objects are cleaned up when you no longer need them. If you have custom objects, look at using the "using statement" and the IDisposable interface.
This link has some good practical advice with regards to freeing up memory / garbage collection etc:
http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx
Look at it this way - is it more efficient to throw out the kitchen garbage when the garbage can is at 10% or let it fill up before taking it out?
By not letting it fill up, you are wasting your time walking to and from the garbage bin outside. This analogous to what happens when the GC thread runs - all the managed threads are suspended while it is running. And If I am not mistaken, the GC thread can be shared among multiple AppDomains, so garbage collection affects all of them.
Of course, you might encounter a situation where you won't be adding anything to the garbage can anytime soon - say, if you're going to take a vacation. Then, it would be a good idea to throw out the trash before going out.
This MIGHT be one time that forcing a GC can help - if your program idles, the memory in use is not garbage-collected because there are no allocations.
The best practise is to not force a garbage collection in most cases. (Every system I have worked on that had forced garbage collections, had underlining problems that if solved would have removed the need to forced the garbage collection, and sped the system up greatly.)
There are a few cases when you know more about memory usage then the garbage collector does. This is unlikely to be true in a multi user application, or a service that is responding to more then one request at a time.
However in some batch type processing you do know more then the GC. E.g. consider an application that.
Is given a list of file names on the command line
Processes a single file then write the result out to a results file.
While processing the file, creates a lot of interlinked objects that can not be collected until the processing of the file have complete (e.g. a parse tree)
Does not keep much state between the files it has processed.
You may be able to make a case (after careful) testing that you should force a full garbage collection after you have process each file.
Another cases is a service that wakes up every few minutes to process some items, and does not keep any state while it’s asleep. Then forcing a full collection just before going to sleep may be worthwhile.
The only time I would consider forcing
a collection is when I know that a lot
of object had been created recently
and very few objects are currently
referenced.
I would rather have a garbage collection API when I could give it hints about this type of thing without having to force a GC my self.
See also "Rico Mariani's Performance Tidbits"
I think the example given by Rico Mariani was good: it may be appropriate to trigger a GC if there is a significant change in the application's state. For example, in a document editor it may be OK to trigger a GC when a document is closed.
There are few general guidelines in programming that are absolute. Half the time, when somebody says 'you're doing it wrong', they're just spouting a certain amount of dogma. In C, it used to be fear of things like self-modifying code or threads, in GC languages it is forcing the GC or alternatively preventing the GC from running.
As is the case with most guidelines and good rules of thumb (and good design practices), there are rare occasions where it does make sense to work around the established norm. You do have to be very sure you understand the case, that your case really requires the abrogation of common practice, and that you understand the risks and side-effects you can cause. But there are such cases.
Programming problems are widely varied and require a flexible approach. I have seen cases where it makes sense to block GC in garbage collected languages and places where it makes sense to trigger it rather than waiting for it to occur naturally. 95% of the time, either of these would be a signpost of not having approached the problem right. But 1 time in 20, there probably is a valid case to be made for it.
I've learned to not try to outsmart the garbage collection. With that said, I just stick to using using keyword when dealing with unmanaged resources like file I/O or database connections.
One case I recently encountered that required manual calls to GC.Collect() was when working with large C++ objects that were wrapped in tiny managed C++ objects, which in turn were accessed from C#.
The garbage collector never got called because the amount of managed memory used was negligible, but the amount of unmanaged memory used was huge. Manually calling Dispose() on the objects would require that I keep track of when objects are no longer needed myself, whereas calling GC.Collect() will clean up any objects that are no longer referred.....
Not sure if it is a best practice, but when working with large amounts of images in a loop (i.e. creating and disposing a lot of Graphics/Image/Bitmap objects), i regularly let the GC.Collect.
I think I read somewhere that the GC only runs when the program is (mostly) idle, and not in the middle of a intensive loop, so that could look like an area where manual GC could make sense.
I think you already listed the best practice and that is NOT to use it unless REALLY necessary. I would strongly recommend looking at your code in more detail, using profiling tools potentially if needed to answer these questions first.
Do you have something in your code that is declaring items at a larger scope than needed
Is the memory usage really too high
Compare performance before and after using GC.Collect() to see if it really helps.
Suppose your program doesn't have memory leakage, objects accumulates and cannot be GC-ed in Gen 0 because:
1) They are referenced for long time so get into Gen1 & Gen2;
2) They are large objects (>80K) so get into LOH (Large Object Heap). And LOH doesn't do compacting as in Gen0, Gen1 & Gen2.
Check the performance counter of ".NET Memory" can you can see that the 1) problem is really not a problem. Generally, every 10 Gen0 GC will trigger 1 Gen1 GC, and every 10 Gen1 GC will trigger 1 Gen2 GC. Theoretically, GC1 & GC2 can never be GC-ed if there is no pressure on GC0 (if the program memory usage is really wired). It never happens to me.
For problem 2), you can check ".NET Memory" performance counter to verify whether LOH is getting bloated. If it is really a issue to your problem, perhaps you can create a large-object-pool as this blog suggests http://blogs.msdn.com/yunjin/archive/2004/01/27/63642.aspx.
I would like to add that:
Calling GC.Collect() (+ WaitForPendingFinalizers()) is one part of the story.
As rightly mentioned by others, GC.COllect() is non-deterministic collection and is left to the discretion of the GC itself (CLR).
Even if you add a call to WaitForPendingFinalizers, it may not be deterministic.
Take the code from this msdn link and run the code with the object loop iteration as 1 or 2. You will find what non-deterministic means (set a break point in the object's destructor).
Precisely, the destructor is not called when there were just 1 (or 2) lingering objects by Wait..().[Citation reqd.]
If your code is dealing with unmanaged resources (ex: external file handles), you must implement destructors (or finalizers).
Here is an interesting example:
Note: If you have already tried the above example from MSDN, the following code is going to clear the air.
class Program
{
static void Main(string[] args)
{
SomePublisher publisher = new SomePublisher();
for (int i = 0; i < 10; i++)
{
SomeSubscriber subscriber = new SomeSubscriber(publisher);
subscriber = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine(SomeSubscriber.Count.ToString());
Console.ReadLine();
}
}
public class SomePublisher
{
public event EventHandler SomeEvent;
}
public class SomeSubscriber
{
public static int Count;
public SomeSubscriber(SomePublisher publisher)
{
publisher.SomeEvent += new EventHandler(publisher_SomeEvent);
}
~SomeSubscriber()
{
SomeSubscriber.Count++;
}
private void publisher_SomeEvent(object sender, EventArgs e)
{
// TODO: something
string stub = "";
}
}
I suggest, first analyze what the output could be and then run and then read the reason below:
{The destructor is only implicitly called once the program ends. }
In order to deterministically clean the object, one must implement IDisposable and make an explicit call to Dispose(). That's the essence! :)
Large objects are allocated on LOH (large object heap), not on gen 0. If you're saying that they don't get garbage-collected with gen 0, you're right. I believe they are collected only when the full GC cycle (generations 0, 1 and 2) happens.
That being said, I believe on the other side GC will adjust and collect memory more aggressively when you work with large objects and the memory pressure is going up.
It is hard to say whether to collect or not and in which circumstances. I used to do GC.Collect() after disposing of dialog windows/forms with numerous controls etc. (because by the time the form and its controls end up in gen 2 due to creating many instances of business objects/loading much data - no large objects obviously), but actually didn't notice any positive or negative effects in the long term by doing so.
One more thing, triggering GC Collect explicitly may NOT improve your program's performance. It is quite possible to make it worse.
The .NET GC is well designed and tuned to be adaptive, which means it can adjust GC0/1/2 threshold according to the "habit" of your program memory usage. So, it will be adapted to your program after some time running. Once you invoke GC.Collect explicitly, the thresholds will be reset! And the .NET has to spent time to adapt to your program's "habit" again.
My suggestion is always trust .NET GC. Any memory problem surfaces, check ".NET Memory" performance counter and diagnose my own code.
Not sure if it is a best practice...
Suggestion: do not implement this or anything when unsure. Reevaluate when facts are known, then perform before/after performance tests to verify.
However, if you can reliably test your code to confirm that calling Collect() won't have a negative impact then go ahead...
IMHO, this is similar to saying "If you can prove that your program will never have any bugs in the future, then go ahead..."
In all seriousness, forcing the GC is useful for debugging/testing purposes. If you feel like you need to do it at any other times, then either you are mistaken, or your program has been built wrong. Either way, the solution is not forcing the GC...
There are some scenarios where there will definitely be very little to no negative impact on your system when forcing a garbage collection e.g. On a date roll/a scheduled time where the system is not in use.
Aside from such times you would need to test performance of your code before and after implementing the forced collect to ensure that it is actually beneficial.
I do NOT recommend manual garbage collection. I assure you that you're not disposing of large objects properly. Make use of the USING statement. Whenever you instantiate an object, be sure to DISPOSE of it when you are through using it. This sample code creates a connection with USING statements. Then it instantiates a shipping label object, uses it, and disposes of it properly.
Using con As SqlConnection = New SqlConnection(DB_CONNECTION_STRING)
con.Open()
Using command As SqlCommand = New SqlCommand(sqlStr, con)
Using reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
code_here()
End While
End Using
End Using
End Using
Dim f1 As frmShippingLabel
f1 = New frmShippingLabel
f1.PrintLabel()
f1.Dispose()