473,597 Members | 2,239 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(IntP tr handle)
{
this.handle = handle;
}

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

private void Dispose(bool disposing)
{
if(!this.dispos ed)
{
if(disposing)
{
component.Dispo se();
}

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

[System.Runtime. InteropServices .DllImport("Ker nel32")]
private extern static Boolean CloseHandle(Int Ptr 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 2026
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(IntP tr handle)
{
this.handle = handle;
}

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

private void Dispose(bool disposing)
{
if(!this.dispos ed)
{
if(disposing)
{
component.Dispo se();
}

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

[System.Runtime. InteropServices .DllImport("Ker nel32")]
private extern static Boolean CloseHandle(Int Ptr 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*@discussion s.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.co m>
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*@discussion s.microsoft.com > wrote in message
news:4E******** *************** ***********@mic rosoft.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(IntP tr handle)
{
this.handle = handle;
}

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

private void Dispose(bool disposing)
{
if(!this.dispos ed)
{
if(disposing)
{
component.Dispo se();
}

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

[System.Runtime. InteropServices .DllImport("Ker nel32")]
private extern static Boolean CloseHandle(Int Ptr 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.PtrToSt ructure is eating
heap, but Marshal.ReadInt Ptr is not. And you have no Dispose for structures.
Also, Message.GetLPar am 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******** ******@TK2MSFTN GP09.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*@discussion s.microsoft.com > wrote in message
news:4E******** *************** ***********@mic rosoft.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(IntP tr handle)
{
this.handle = handle;
}

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

private void Dispose(bool disposing)
{
if(!this.dispos ed)
{
if(disposing)
{
component.Dispo se();
}

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

[System.Runtime. InteropServices .DllImport("Ker nel32")]
private extern static Boolean CloseHandle(Int Ptr 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
6044
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 Dispose method of IDbConnection. This Dispose method is called from a destructor. In the dispose method, i also call GC.SuppressFinalize(this) so as to avoid finalizer. All this was OK untill i came across one article that says - not to call...
4
1918
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 release refrence from memory ? E. If it release object from memory then what GC does ? 2. Which class can have dispose method ? class which is member of IDispose Inteface 3. Where we should use abstract / Interface ?
15
2054
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 earlier. Thus, if you think the unmanaged resources are important, you call Dispose explicitly. My question is what's the criteria to decide the unmanaged resources are important.
9
1247
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 automatically, including chaining calls to Dispose. (There is no Dispose pattern)" but Dispose can thrown an exception. Is the exception supressed?
17
1684
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.... This is found in the SqlHelper class - Dim cn As New SqlConnection(connectionString)
10
1946
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, CN) Dim DR As OleDbDataReader = CMD.ExecuteReader()
6
3575
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. what is the correct way of implementing IDisposable.Dispose? 3. what is the preferred way, if there is one over the other, of calling the Dispose method on an object that implements IDisposable. Is it the way that uses the "using(object){}" construct...
2
1908
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 PictureBox control. The app works well until trying to go to another record from a record where there is not a file name present. If no file name, a label displays that an image is needed. But if you try to go to another record with an image, that...
3
1542
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 the IDisposable interface. C. Derive the generic class from the IDisposable class.
0
7969
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7886
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8272
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8258
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5431
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3886
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3927
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2404
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1494
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.