473,322 Members | 1,719 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,322 software developers and data experts.

A question about Dispose method

xyu
Hello,

First I would like to thank anyone who helps me, much appreciated.

I'm a c++ programmer just started using c#. I'm writing some big hash table so I want to actively take my object off the heap and release the memory when it's deleted from the hash table so that GC recollection does not need to run that frequently.

I read up examples about Dispose method in MSDN. What I find very strange is that it's all talking about how to release managed and unmanaged resources inside this object but there isn't any code to release the object itself? How is that managed?

Example(from MSDN)

public class DisposeExample
{
public class MyResource: IDisposable
{
private IntPtr handle;
private Component component = new Component();
private bool disposed = false;

public MyResource(IntPtr handle)
{
this.handle = handle;
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

private void Dispose(bool disposing)
{
if(!this.disposed)
{
if(disposing)
{
component.Dispose();
}

CloseHandle(handle);
handle = IntPtr.Zero;
}
disposed = true;
}

[System.Runtime.InteropServices.DllImport("Kernel32 ")]
private extern static Boolean CloseHandle(IntPtr handle);

~MyResource()
{
Dispose(false);
}
}
public static void Main()
{
MyResource obj = new MyResource( //whatever here );

// I call this function to clear all the resource obj holds
// What why I can not find any code which take obj itself off the heap?????
obj.Dispose();
}
}

Nov 16 '05 #1
4 2002
The example that you are quoting is specifically targetted at releasing unmanaged resources, hence there is a need to tell GC to not perform its finalization and let us do the releasing of objects because we know how a specific unmanaged object/resource behaves and allocates and deallocates stuff. That kind of example is not focused on managed objects because thats automatically done for you by the runtime in cooperation with GC. Now if you do want your managed objects to be collected when you want
try null-ing your object and than just calling GC.Collect() after that, you 'll see that the memory that your object was occupying is released.
example:
class ctype
{
int [] obj;//= new int[1000000];
string p="hello";

public void allocate()
{
obj= new int [10000000];
}
}

[STAThread]
static void Main(string[] args)
{
ctype obj= new ctype();
obj.allocate(); //memory goes up
obj= null; // nothing happens. GC is watching CNN
GC.Collect(); // object collected

}

Now there can be one more case in which you have written some cleanup logic in a Dispose method and you want that called as soon as your object goes out of scope. To ensure that this happens, you can implement an IDisposeable iterface and writiing your code in a "using" block as (from msdn):

Font MyFont3 = new Font("Arial", 10.0f);
using (MyFont3)
{
// use MyFont3
} // compiler will call Dispose on MyFont3

Also, do some reading on Undeterministic Finalization as you are new to C#.

Hope that helps.

Abubakar.
http://joehacker.blogspot.com/

"xyu" wrote:
Hello,

First I would like to thank anyone who helps me, much appreciated.

I'm a c++ programmer just started using c#. I'm writing some big hash table so I want to actively take my object off the heap and release the memory when it's deleted from the hash table so that GC recollection does not need to run that frequently.

I read up examples about Dispose method in MSDN. What I find very strange is that it's all talking about how to release managed and unmanaged resources inside this object but there isn't any code to release the object itself? How is that managed?

Example(from MSDN)

public class DisposeExample
{
public class MyResource: IDisposable
{
private IntPtr handle;
private Component component = new Component();
private bool disposed = false;

public MyResource(IntPtr handle)
{
this.handle = handle;
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

private void Dispose(bool disposing)
{
if(!this.disposed)
{
if(disposing)
{
component.Dispose();
}

CloseHandle(handle);
handle = IntPtr.Zero;
}
disposed = true;
}

[System.Runtime.InteropServices.DllImport("Kernel32 ")]
private extern static Boolean CloseHandle(IntPtr handle);

~MyResource()
{
Dispose(false);
}
}
public static void Main()
{
MyResource obj = new MyResource( //whatever here );

// I call this function to clear all the resource obj holds
// What why I can not find any code which take obj itself off the heap?????
obj.Dispose();
}
}

Nov 16 '05 #2
xyu <xy*@discussions.microsoft.com> wrote:
I read up examples about Dispose method in MSDN. What I find very
strange is that it's all talking about how to release managed and
unmanaged resources inside this object but there isn't any code to
release the object itself? How is that managed?


The garbage collector is responsible for actually destroying objects
and freeing the memory associated with them. You don't need to handle
that at all - although if you have a reachable reference to an object
you don't need, in some cases (very, very rare IME) it may be worth
setting the reference to null to help the garbage collector.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #3
The GC handles all of the details, and as others have pointed out, Dispose()
is for the times when you have unmanaged resources.

You should avoid calling GC.Collect() directly, as you will likely increase
the amount of time spent by the GC process. There is a fair amount of
overhead to a GC, so if you call it very time an object could be free'd,
you'd be wasting a large amount of time.

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://weblogs.asp.net/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
"xyu" <xy*@discussions.microsoft.com> wrote in message
news:4E**********************************@microsof t.com...
Hello,

First I would like to thank anyone who helps me, much appreciated.

I'm a c++ programmer just started using c#. I'm writing some big hash table so I want to actively take my object off the heap and release the
memory when it's deleted from the hash table so that GC recollection does
not need to run that frequently.
I read up examples about Dispose method in MSDN. What I find very strange is that it's all talking about how to release managed and unmanaged
resources inside this object but there isn't any code to release the object
itself? How is that managed?
Example(from MSDN)

public class DisposeExample
{
public class MyResource: IDisposable
{
private IntPtr handle;
private Component component = new Component();
private bool disposed = false;

public MyResource(IntPtr handle)
{
this.handle = handle;
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

private void Dispose(bool disposing)
{
if(!this.disposed)
{
if(disposing)
{
component.Dispose();
}

CloseHandle(handle);
handle = IntPtr.Zero;
}
disposed = true;
}

[System.Runtime.InteropServices.DllImport("Kernel32 ")]
private extern static Boolean CloseHandle(IntPtr handle);

~MyResource()
{
Dispose(false);
}
}
public static void Main()
{
MyResource obj = new MyResource( //whatever here );

// I call this function to clear all the resource obj holds
// What why I can not find any code which take obj itself off the heap????? obj.Dispose();
}
}

Nov 16 '05 #4
Also when you don't call it, you might finish with out of memory errors and
thousands of old objects floating in heap, which GC did not process just
because application was in tight loop. So, you have to choose - what is more
important in your case.

There are some hints in
http://msdn.microsoft.com/architectu...l/scalenet.asp
on what to keep in mind. Calling GC.Collect is really last resort and I
agree here with Eric. However, disposing or nulling is another issue.
Sometimes even simple setting of reference to null helps GC to collect
efficiently. I guess it depends how quickly you create and dispose your
objects when running and how much time you give GC to work.

It is expected that object is taken out of heap when last reference to it is
going out of scope or is explicitly nulled. However, when last reference is
nulled say only after couple of hours, which is common with hashtables, GC
might be "confused".

I find it also "confusing" when people are pointing out that Dispose is for
unmanaged resources. The rule is that if object is IDisposable you must
dispose it. You never know which resources are used in the object.

What I find surprising, is that for example Marshal.PtrToStructure is eating
heap, but Marshal.ReadIntPtr is not. And you have no Dispose for structures.
Also, Message.GetLParam method allocates from heap. These are managed
methods, which have no relation to Dispose yet. I think, here MS did "small"
mistake. I understand that you never know what kind of structure will be
instantiated, however heap-allocated ones must be disposable.

So, my last advice is - do what you want, because general recommendations
are working "generally". But at the end of the day use profiler.

HTH
Alex
"Eric Gunnerson [MS]" <er****@online.microsoft.com> wrote in message
news:eY**************@TK2MSFTNGP09.phx.gbl...
The GC handles all of the details, and as others have pointed out, Dispose() is for the times when you have unmanaged resources.

You should avoid calling GC.Collect() directly, as you will likely increase the amount of time spent by the GC process. There is a fair amount of
overhead to a GC, so if you call it very time an object could be free'd,
you'd be wasting a large amount of time.

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://weblogs.asp.net/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights. "xyu" <xy*@discussions.microsoft.com> wrote in message
news:4E**********************************@microsof t.com...
Hello,

First I would like to thank anyone who helps me, much appreciated.

I'm a c++ programmer just started using c#. I'm writing some big hash table so I want to actively take my object off the heap and release the
memory when it's deleted from the hash table so that GC recollection does
not need to run that frequently.

I read up examples about Dispose method in MSDN. What I find very

strange is that it's all talking about how to release managed and unmanaged
resources inside this object but there isn't any code to release the object itself? How is that managed?

Example(from MSDN)

public class DisposeExample
{
public class MyResource: IDisposable
{
private IntPtr handle;
private Component component = new Component();
private bool disposed = false;

public MyResource(IntPtr handle)
{
this.handle = handle;
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

private void Dispose(bool disposing)
{
if(!this.disposed)
{
if(disposing)
{
component.Dispose();
}

CloseHandle(handle);
handle = IntPtr.Zero;
}
disposed = true;
}

[System.Runtime.InteropServices.DllImport("Kernel32 ")]
private extern static Boolean CloseHandle(IntPtr handle);

~MyResource()
{
Dispose(false);
}
}
public static void Main()
{
MyResource obj = new MyResource( //whatever here );

// I call this function to clear all the resource obj holds
// What why I can not find any code which take obj itself off
the heap?????
obj.Dispose();
}
}


Nov 16 '05 #5

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

Similar topics

3
by: faktujaa | last post by:
Hi All, A small confusion. I have defined a connection class that has System.Data.IDbConnection as a member variable and implements IDisposable interface. I have implemented Dispose method to call...
4
by: RiteshDotNet | last post by:
..net Frame work 1. Dispose Method what it does ? A. who its call / when it calls ? B. Is it fire automatically ? c. When dispose method is call what it does ? D. Release a Object from memory or...
15
by: Sam Sungshik Kong | last post by:
Hello! A disposable object's Dispose() method can be called either explicitly by the programmer or implicitly during finalization. If you call Dispose, the unmanaged resources are released...
9
by: Hasani \(remove nospam from address\) | last post by:
I was reading a ppt ( http://www.gotdotnet.com/team/pdc/4064/tls310.ppt ) and came aross this statement. "Users can leverage a destructor. The C++ compiler generates all the Dispose code...
17
by: Bob Lehmann | last post by:
Hi, My understanding is that Dispose() should not be used for destroying a connection object, and that Close() is preferred. However, in one of MS's Quickstart Apps I see this being used.... ...
10
by: mg | last post by:
I'm migrating from VB6 and have a question about using 'Using' and the best way to use it. Here is a example of a small bit of code: dbConx("open") Using CN Dim CMD As New OleDbCommand(sSQL,...
6
by: Water Cooler v2 | last post by:
I heard from someone that we must not implement IDisposable for all classes. Can someone please tell me: 1. the reason why we must not implement IDisposable for all the classes we write. 2....
2
by: =?Utf-8?B?RU1hbm5pbmc=?= | last post by:
I'm developing an application for my customer to log info about photos/images he has done. Each record contains the file name of the image and displays the image based on that file name in a...
3
by: Tony Johansson | last post by:
Hello! I have the following question: You are creating a generic class, and you need to dispose of the generic objects. How can you do this? A. Call the Object.Dispose method. B. Implement...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.