473,386 Members | 1,766 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Clean up after yourself!

A handy piece of code...

Put this in your Dipose() methods and it will do all your clean up for.
Just need to add support for unregistering events and all our memory leaks
will be gone!

public void Disposer()
{
Type type = this.GetType();
if (type != null)
{
foreach(FieldInfo fi in type.GetFields(BindingFlags.NonPublic |
BindingFlags.Instance))
{
object field = fi.GetValue(this);
if (field is IDisposable)
{
((IDisposable)field).Dispose();
Console.WriteLine("disposed field:" + fi.Name);
}
}
}
}

Eric Cadwell
http://www.origincontrols.com
Nov 15 '05 #1
3 1476
Hi Eric!

Thanks for this piece of code... I'll use it well! :)
Two question though... do you have any examples of unregistering events in
this contex?
Does this method slow down the application?

Thanks,
saso

"Eric Cadwell" <ec******@ns.insight.com> wrote in message
news:uF*************@tk2msftngp13.phx.gbl...
A handy piece of code...

Put this in your Dipose() methods and it will do all your clean up for.
Just need to add support for unregistering events and all our memory leaks
will be gone!

public void Disposer()
{
Type type = this.GetType();
if (type != null)
{
foreach(FieldInfo fi in type.GetFields(BindingFlags.NonPublic |
BindingFlags.Instance))
{
object field = fi.GetValue(this);
if (field is IDisposable)
{
((IDisposable)field).Dispose();
Console.WriteLine("disposed field:" + fi.Name);
}
}
}
}

Eric Cadwell
http://www.origincontrols.com

Nov 15 '05 #2
Yes, but remember that you have to call the method :-)

If you implement the C# destructor (Finalize) to callk your Dispose method,
then you have another issue - if your fields are objects that have
finalizers then they'll be queued to be finalized too, and maybe finalized
before your object's Destructor (Finalize) is called.

This is why components implement a protected version of Dispose that takes a
bool parameter. This parameter has a value of false if the method is called
by the finalizer and true if it is called by the publicly accessible
IDisposable.Dispose. If the parameter is true then both managed and
unmanaged objects should be disposed, if it is false then only unmanaged
objects should be disposed.

Note that your code will not prevent memory leaks because you are disposing
managed objects and managed objects that hold resources should be disposable
and will have a finalizer as a safety measure so that when a GC occurs the
resources are released. The biggest source of leaks is from unmanaged
objects, which your code does not release.

Richard
--
my email ev******@zicf.bet is encrypted with ROT13 (www.rot13.org)

Eric Cadwell wrote:
A handy piece of code...

Put this in your Dipose() methods and it will do all your clean up
for. Just need to add support for unregistering events and all our
memory leaks will be gone!

public void Disposer()
{
Type type = this.GetType();
if (type != null)
{
foreach(FieldInfo fi in type.GetFields(BindingFlags.NonPublic |
BindingFlags.Instance))
{
object field = fi.GetValue(this);
if (field is IDisposable)
{
((IDisposable)field).Dispose();
Console.WriteLine("disposed field:" + fi.Name);
}
}
}
}

Eric Cadwell
http://www.origincontrols.com

Nov 15 '05 #3
The biggest issue I've found are event subscriptions to static (root)
objects. It happens within the framework code (i.e. DateTimePicker) and I
even recreated the same mistake in my code. The event registration prevents
all objects from being disposed. In this case, the object is never put in
the finalization queue because it believes the object is still in use base
on the implicit root reference. In such a case managed and unmanaged
resources are being leaked unless I manually invoke Dispose on everything
(which at best allows the unmanaged resource to be reclaimed). On that note,
it's much cleaner to run my function than to embed explicit calls for each
object instance in the Dispose() method.

If I could enhance that sample to delete event registrations and nullify the
reference it would go a long way to improve performance.

-Eric
Nov 15 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: ma.giorgi | last post by:
hi to all! I've tried in all the way but I can't find a solution I show you an example: I have the following html code: <div id="aaa">text inside<br/> a div</div><span class="bbb"> text inside...
5
by: Rob R. Ainscough | last post by:
I have a moderately sized web application (30 pages, and 20 DLLs) that takes 10-20 minutes to "Build Solution" after I do a "Clean Solution" -- this is ONLY apparent after a "Clean Solution" I...
11
by: tobiah | last post by:
Suppose I do: myfoo = Foo('grapes', 'oranges') And in the __init__() of Foo, there is a real problem with the consumption of fruit. Is there a clean way to ensure that myfoo will be None...
7
by: Ragnar Agustsson | last post by:
Hi all I have been wandering about the best way to sandbox memory leaks in 3rd party libraries when using them from the .Net framework. I have a 3rd party library, written in C++, that leaks a...
232
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first...
9
by: jd | last post by:
I am looking for python code (working or sample code) that can take an html document created by Microsoft Word and clean it up (if you've never had to look at a Word-generated html document,...
25
by: Koliber (js) | last post by:
sorry for my not perfect english i am really f&*ckin angry in this common pattern about dispose: ////////////////////////////////////////////////////////// Public class...
10
by: Greg Lovern | last post by:
I have a very large html table created by MS Word, saved as it's "Web Page, Filtered" file type. Every html table cell has lots of formatting tags. Most of the file size is that formatting. Is...
8
by: plenty900 | last post by:
Hello, I'm trying to build a large project, and I've found that when something doesn't compile properly, and I attempt to re-build it, Visual C++ Express doesn't make a new attempt. So then I...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.