Garbage Collection & Memory Leaks.
-
I am using the Task Manager and it shows that each iteration of a new large form grows the exe memory usage by around 3MB (grows by 20MB during form execution, drops by around 17MB when the form is closed and GC.GetTotalMemory( true ) is called). After opening, running and closing just a few series of forms the app memory usage grows from 30MB to over 60MB, User Objects grows from 60 odd to over 130 and GDI objects grows from 80 plus to over 400. GC.GetTotalMemory( true ) returns around 7MB (Probably close to the correct value for chached data). I see that all class objects I create in the application are GC'ed except the forms and in the forms Dispose method I Close all appropriate objects and set all appropriate references to null. My client requires that the application be run under Citrix and the application is expected to remain open on the user desktop for the whole day. That means that over the course of the day the application could grow by several hundred megabytes multiplied by the number of Citrix clients on the server to me adds up to a disaster.
The Task Manager is useless for this. There are a number of performance monitors included, but I would recommend learning the details of the GC engine before trying to use them. If your system is not currently memory limited, there is no reason for the garbage collector to kick in. It's not like unused memory is doing anyone any good, and the longer it can wait, the less risk of promoting data to new generations without need - after all, the more it has promoted, the harder it will be to release it if it is actually needed. I think I have seen claims it will be more inclined to free it if you minimize the app, but I have not looked into this. As long as you have not left something hanging without calling Dispose I doubt you have a problem. And no need to run around setting things to null in the Dispose method by the way, this is not VB. If you no longer have a reference to you form, it will be cleared whenever the GC think it is best. PS: Just realized another potential pitfall - if you have any delegates pointing to your form from an object not yet ready for GC, then it will keep your form alive. Typically this would be if your form was listening to an event in the domain layer. If it is the case, unsubscribe in the Dispose method.
-
I have added a menu item to my Mdi container form which calls GC.GetTotalMemory( true ); and I report the returned value. GC.GetTotalMemory( true ) should force GC and the destructor (Finalize) as appropriate. This happens for all other class instances EXCEPT Forms displayed with the Show() method. (Modal Forms displayed with the ShowDialog method are GC'ed.)
You should never force the GC to run. All forms, no matter how they are shown, are kept in memory to be shown again if they are reused. It's a waste of time worrying about the memory a form uses, are you using a ZX81 ? Just make sure you call Dispose as appropriate and trust the GC to do it's job.
Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )
-
C# is not C++. Your destructor will be called, one day. Maybe before, maybe after your system collapses. To manage resources in C#, you need to call Dispose whenever disposing of any resource.
Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )
For most variables if you declare them in a function: private void DoSomething() { MyClass yada; yada = new MyClass(); } Then yada gets garbage collected at the end of the function. But if we do: private void DoSomething() { Form2 yada; yada = new Form2(); yada.Show(); } Then yada doesn't get GC. As Christian says, Dispose() will set it ready for GC, but it will take its own sweet time. However do you really need to keep creating this form again and again, can't you declare it as an object in you main class, that you just show/hide when you need it. That will stop the memory allocation each time.
-
For most variables if you declare them in a function: private void DoSomething() { MyClass yada; yada = new MyClass(); } Then yada gets garbage collected at the end of the function. But if we do: private void DoSomething() { Form2 yada; yada = new Form2(); yada.Show(); } Then yada doesn't get GC. As Christian says, Dispose() will set it ready for GC, but it will take its own sweet time. However do you really need to keep creating this form again and again, can't you declare it as an object in you main class, that you just show/hide when you need it. That will stop the memory allocation each time.
No, what I'm saying is this - private void DoSomething() { (new Form2()).Show(); } When Form2 is Closed (user action) Dispose(true) is automatically called by the CLR. All fine. But after calls to GC.Collect() or GC.GetTotalMemory(true) (both of which should force GC) the form (plus all the controls for the form are never GC'd) However, private void DoSomething() { (new Form2()).ShowDialog(); } When Form2 is Closed (user action) Dispose(true) is NOT automatically called by the CLR and shortly after, typically when further memory allocations are required the form gets CG'd. My point is then that (new Form2()).Show(); requires that a reference to the form be promoted somewhere within the CLR (or O/S) to keep track of the form as the DoSomething() method completes immediately. The internal reference to the form is never removed, even when the form is closed (only when the app terminates) so the form (and all of the form's controls) can never be GC'd. The typical base managed heap allocation for a complex form instance (multiple pages, multiple controls) appears to be around 1 to 2 megabytes (not including data) which remains after the form is Disposed. The application (an Mdi ERP solution) has around 500 forms and has a user base of around 150 users within the client organisation. The client decision to distribute the solution through Citrix is directly impacted by the cumulative effect of additional memory usage over 20 to 30 users on a typical Citrix server box. So if no way can be found to force the CLR (or O/S) to relinquish the reference to the form after it is closed and therefore eventually be GC'd then the client decision to distribute the solution through Citrix will need to be seriously re-evaluated. (Not the case for ShowDialog() which does not terminate the DoSomething() method until the form is Closed()) (therefore no promotion is necessary)
-
You should never force the GC to run. All forms, no matter how they are shown, are kept in memory to be shown again if they are reused. It's a waste of time worrying about the memory a form uses, are you using a ZX81 ? Just make sure you call Dispose as appropriate and trust the GC to do it's job.
Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )
Hi Christian, Could you please have a look at my reply to CaiX message. No I am not using ZX81, however the client is using Citrix with some 150 user base so memory usage does impact server utilisation. Also, how a form is shown does impact. ShowDialog() does GC the form. (and only the internal Finalize() method calls Dispose as Dispose(false) whereas Show() automatically calls Dispose(true) on Close and never GC's the form.
-
No, what I'm saying is this - private void DoSomething() { (new Form2()).Show(); } When Form2 is Closed (user action) Dispose(true) is automatically called by the CLR. All fine. But after calls to GC.Collect() or GC.GetTotalMemory(true) (both of which should force GC) the form (plus all the controls for the form are never GC'd) However, private void DoSomething() { (new Form2()).ShowDialog(); } When Form2 is Closed (user action) Dispose(true) is NOT automatically called by the CLR and shortly after, typically when further memory allocations are required the form gets CG'd. My point is then that (new Form2()).Show(); requires that a reference to the form be promoted somewhere within the CLR (or O/S) to keep track of the form as the DoSomething() method completes immediately. The internal reference to the form is never removed, even when the form is closed (only when the app terminates) so the form (and all of the form's controls) can never be GC'd. The typical base managed heap allocation for a complex form instance (multiple pages, multiple controls) appears to be around 1 to 2 megabytes (not including data) which remains after the form is Disposed. The application (an Mdi ERP solution) has around 500 forms and has a user base of around 150 users within the client organisation. The client decision to distribute the solution through Citrix is directly impacted by the cumulative effect of additional memory usage over 20 to 30 users on a typical Citrix server box. So if no way can be found to force the CLR (or O/S) to relinquish the reference to the form after it is closed and therefore eventually be GC'd then the client decision to distribute the solution through Citrix will need to be seriously re-evaluated. (Not the case for ShowDialog() which does not terminate the DoSomething() method until the form is Closed()) (therefore no promotion is necessary)
Instead of pounding on people to tell you something about your code, that they've never seen, why not test it out and beat on it until you get it to fail, or you manage to see that the GC does know what it's doing. The GC doesn't HAVE to collect objects if it doesn't see the need to, or, more precisely, it doesn't have to release managed memory back to Windows unless Windows wants it back. If an object is collected, the memory goes back to the managed heap, not back to Windows!
Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
2006, 2007 -
Hi Christian, Could you please have a look at my reply to CaiX message. No I am not using ZX81, however the client is using Citrix with some 150 user base so memory usage does impact server utilisation. Also, how a form is shown does impact. ShowDialog() does GC the form. (and only the internal Finalize() method calls Dispose as Dispose(false) whereas Show() automatically calls Dispose(true) on Close and never GC's the form.
OK, sounds like you're learning a lot about how the GC works. So, make your forms member variables, which is the only half reasonable way to create forms you call Show on, anyhow. Then, recycle the same form, instead of creating them all the time.
Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )
-
The Task Manager is useless for this. There are a number of performance monitors included, but I would recommend learning the details of the GC engine before trying to use them. If your system is not currently memory limited, there is no reason for the garbage collector to kick in. It's not like unused memory is doing anyone any good, and the longer it can wait, the less risk of promoting data to new generations without need - after all, the more it has promoted, the harder it will be to release it if it is actually needed. I think I have seen claims it will be more inclined to free it if you minimize the app, but I have not looked into this. As long as you have not left something hanging without calling Dispose I doubt you have a problem. And no need to run around setting things to null in the Dispose method by the way, this is not VB. If you no longer have a reference to you form, it will be cleared whenever the GC think it is best. PS: Just realized another potential pitfall - if you have any delegates pointing to your form from an object not yet ready for GC, then it will keep your form alive. Typically this would be if your form was listening to an event in the domain layer. If it is the case, unsubscribe in the Dispose method.
OK so forms created with the VS designer have fields added to the form class to hold the instance creations of each of the controls added through the designer. Any events added during the designer phase are still active at the form Dispose stage. So there is a circular reference between the control event delegate ( textBox1.SomeEvent += new EventHandler(this.SomeMethod); ) and control create instance field ( TextBox textBox1; & this.textBox1 = new TextBox(); ) which prevails after the Dispose method is completed. So I will at least need to add to the Dispose method textBox1.SomeEvent -= new EventHandler(this.SomeMethod); etc.
-
OK so forms created with the VS designer have fields added to the form class to hold the instance creations of each of the controls added through the designer. Any events added during the designer phase are still active at the form Dispose stage. So there is a circular reference between the control event delegate ( textBox1.SomeEvent += new EventHandler(this.SomeMethod); ) and control create instance field ( TextBox textBox1; & this.textBox1 = new TextBox(); ) which prevails after the Dispose method is completed. So I will at least need to add to the Dispose method textBox1.SomeEvent -= new EventHandler(this.SomeMethod); etc.
No, this is not VB. :) You need to unsubscribe from events on objects you still hold a reference to. If you do not keep a reference to the form once it is closed, the GC will be able to release it (if it can be bothered), no matter how many references it has to itself (or other objects for that amtter, as long as they combined can't be referenced anymore). I am still feeling you are spending a lot of time solving a problem you do not know if you have in the first place.
-
No, this is not VB. :) You need to unsubscribe from events on objects you still hold a reference to. If you do not keep a reference to the form once it is closed, the GC will be able to release it (if it can be bothered), no matter how many references it has to itself (or other objects for that amtter, as long as they combined can't be referenced anymore). I am still feeling you are spending a lot of time solving a problem you do not know if you have in the first place.
I think maybe your right. If I minimize the main mdi container form then maximize the task manager shows memory allocation has been reset to the expected minimum value. I guess the GC is saying its cheaper to do a full tidy up on minimize than save the untidied bloat to cache. Thanks.
-
OK, sounds like you're learning a lot about how the GC works. So, make your forms member variables, which is the only half reasonable way to create forms you call Show on, anyhow. Then, recycle the same form, instead of creating them all the time.
Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )
Thanks for your help. I believe I've sorted the problem. If I minimize and maximize the main mdi form the Task Manager reports a low resized memory. So the GC really only works when it needs too and if there is no memory pressure it just lets the app grow. Thanks.