473,796 Members | 2,569 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

garbage collection

Hello,

I have a c# application that creates a timer to fire every minute using
multithreading. On every minute it calls a Ping class that I made using
sockets.
It creates a new ping class then sets it to null when it’s done.

I noticed every time this class gets created I see the memory keeps getting
larger.
I think I should add Idisposable to my ping class and dispose of the memory
after the class is set to null.

Can someone give me their thoughts on this and maybe an example on how to
use the Idisposable class?
Thanks

Nov 17 '05
36 1938

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Willy Denoyette [MVP] <wi************ *@telenet.be> wrote:
"The Crow" <q> wrote in message
news:OE******** ******@TK2MSFTN GP15.phx.gbl...
> socket is managed, socket implements idisposable, so no matter when,
> when
> socket will be garbage collected (sure it will be), its Dispose()
> method
> will be called.why bother with idisposable? am i missing something?


Dispose is not called when the sockect is GC'd. Dispose must be called
explicitely.


As far as I can see, it *is* called when it's finalized.

This short program demonstrates that:

using System;
using System.Net.Sock ets;

public class Test : Socket
{
public Test(AddressFam ily addressFamily,
SocketType socketType,
ProtocolType protocolType)
: base (addressFamily, socketType, protocolType)
{
}

protected override void Dispose (bool disposing)
{
base.Dispose(tr ue);
Console.WriteLi ne ("Disposed!" );
}

static void Main()
{
Test t = new Test(AddressFam ily.InterNetwor k,
SocketType.Stre am,
ProtocolType.IP );

t = null;
GC.Collect();
GC.WaitForPendi ngFinalizers();
Console.WriteLi ne ("Finishing" );
}
}

Are you trying to stress the difference between something being GC'd
and something being finalized?

--

To further illustrate my point, following is a sample (based on yours) that
illustrates how easy it is to block the finalizer thread.
This sample includes a class DogWrapper that wraps a simple COM object Dog,
in Main I create an instance of Dog and calls a method on it.

The output (except ***) looks like:

Woef!!
Test Disposed!
Finalizing DogWrapper !
*** 5 seconds delay here (10 * 0.5 secs.)
Finishing
Dog object Disposed!
Test Disposed!
Test Disposed!
Test Disposed!
Test Disposed!
Test Disposed!
Test Disposed!
Test Disposed!
Test Disposed!
Test Disposed!

Notice the time when "Finishing" is output... at program exit time, but
before the finalizer runs! That means that from the moment on that the
"Finalizer thread" enters DogWrapper's Finalize (ReleaseComObje ct to be
precise) it will block until it gets aborted and restarted by the CLR at
process shutdown time.
Note that this doesn't stop the GC nor the program to run (but how long?),
however, you will leak the resources you intended to release through the
destructor calling Dispose(false) and your "finalizabl e instances" will
finally exhaust the GC heap.
Note that the same can happen if the finalizer thread gets stuck (or blocks
for a long time) in unmanaged code.

using System;
using System.Net.Sock ets;
using System.Reflecti on;
using System.Runtime. InteropServices ;
using Project; // IA for Dog

public class DogWrapper : IDisposable
{
Dog madDog;
public void Bark()
{
madDog= new Dog();
madDog.Bark();
}
public void Dispose()
{
this.Dispose(tr ue);
GC.SuppressFina lize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!this.dispos ed)
{
Marshal.Release ComObject(madDo g);
GC.Collect();
GC.WaitForPendi ngFinalizers();
madDog= null;
Console.WriteLi ne ("Dog object Disposed!");
}
this.disposed = true;
}
~T()
{
Console.WriteLi ne ("Finalizing DogWrapper !");
Dispose(false);
}
}
public class Test : Socket
{
public Test(AddressFam ily addressFamily,
SocketType socketType,
ProtocolType protocolType)
: base (addressFamily, socketType, protocolType)
{
}

protected override void Dispose (bool disposing)
{
base.Dispose(tr ue);
Console.WriteLi ne ("Test Disposed!");
}
[STAThread]
static void Main()
{
T te = new T();
GC.Collect();
Console.WriteLi ne(te.GetVersio n());
for (int i = 0; i < 10; i++)
{
Test t = new Test(AddressFam ily.InterNetwor k,
SocketType.Stre am,
ProtocolType.IP );
GC.Collect();
System.Threadin g.Thread.Sleep( 500);
}
Console.WriteLi ne ("Finishing" );
}
}

Nov 17 '05 #31
Willy Denoyette [MVP] <wi************ *@telenet.be> wrote:
Hmm...I suppose it's me you are replying to, right?
When a class implement IDisposable it better adheres to the disposable
pattern, that is, a type that implements IDisposable should also have a
finalizer (called a destructor in C#), and that finalizer should call
Dispose(false).


Not all classes that implement IDisposable need a finalizer - indeed, I
would argue that *most* don't.

StreamReader is a good example of this - it implements IDisposable to
close the stream it wraps, but it doesn't need a finalizer because it
doesn't *directly* hold any unmanaged resources. Instead, it relies on
teh stream that it wraps having a finalizer.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #32
then in our example, the socket wrapper class doesnt have to call dispose of
socket. because socket.Dispose( ) will be called by the runtime. (probably in
the same garbage collection run.) but what if the socket object in the
wrapper object referenced by another object outside of the wrapper object?
Nov 17 '05 #33

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Willy Denoyette [MVP] <wi************ *@telenet.be> wrote:
Hmm...I suppose it's me you are replying to, right?
When a class implement IDisposable it better adheres to the disposable
pattern, that is, a type that implements IDisposable should also have a
finalizer (called a destructor in C#), and that finalizer should call
Dispose(false).


Not all classes that implement IDisposable need a finalizer - indeed, I
would argue that *most* don't.

StreamReader is a good example of this - it implements IDisposable to
close the stream it wraps, but it doesn't need a finalizer because it
doesn't *directly* hold any unmanaged resources. Instead, it relies on
teh stream that it wraps having a finalizer.


Agreed, but I was talking about base types, and - sorry about the
confusion - what I said is not what I meant.
What I meant to say was, that every type that has a finalizer should
implement IDisposable. This gives users of the type a means to perform
deterministic clean-up of the same resources which the finalizer is
responsible for.
Sure, you may also implement Dispose on types without finalizers, e.g when
transitively disposing of object state or when using types which manage
their resources with finalizers allready.
Note that value types are an exception because they can't have a finalizer,
but I think this is a very simple rule; If you have (say need) a finalizer,
you want Dispose().

Willy.
Nov 17 '05 #34

"Willy Denoyette [MVP]" <wi************ *@telenet.be> wrote in message
news:ud******** ******@TK2MSFTN GP10.phx.gbl...

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Willy Denoyette [MVP] <wi************ *@telenet.be> wrote:
Hmm...I suppose it's me you are replying to, right?
When a class implement IDisposable it better adheres to the disposable
pattern, that is, a type that implements IDisposable should also have a
finalizer (called a destructor in C#), and that finalizer should call
Dispose(false).


Not all classes that implement IDisposable need a finalizer - indeed, I
would argue that *most* don't.

StreamReader is a good example of this - it implements IDisposable to
close the stream it wraps, but it doesn't need a finalizer because it
doesn't *directly* hold any unmanaged resources. Instead, it relies on
teh stream that it wraps having a finalizer.


I forgot to say in my previous reply that StreamReader does not "implement"
IDisposable it just implements Dispose(bool) that calls it's base
(TextReader.Dis pose(bool)) which implements IDisposable though.

Willy.


Nov 17 '05 #35
<"The Crow" <q>> wrote:
then in our example, the socket wrapper class doesnt have to call dispose of
socket. because socket.Dispose( ) will be called by the runtime. (probably in
the same garbage collection run.) but what if the socket object in the
wrapper object referenced by another object outside of the wrapper object?


A wrapper class shouldn't have a finalizer, but it *should* implement
IDisposable to allow the user to dispose of the "wrapped" resource
early.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #36
Thanks everyone

"Brad Wood" wrote:
I believe this snippet:
<snip>
try
{
Encoding ASCII = Encoding.ASCII;
IPEndPoint hostEndPoint;
IPAddress hostAddress = System.Net.IPAd dress.Loopback;
int conPort = port;
string Get = "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nCo nnection:
Close\r\n\r\n";

Byte[] ByteGet = ASCII.GetBytes( Get);
byte[] RecvBytes = new byte[256];
hostEndPoint = new IPEndPoint(host Address, conPort);
Socket s= new Socket(AddressF amily.InterNetw ork, SocketType.Stre am,
ProtocolType.Tc p);
s.Connect(hostE ndPoint);
s.Send(ByteGet, ByteGet.Length, 0);

s.Close();
}
catch
{
}
</snip>

could be changed to:

<NewSnip>
Encoding ASCII = Encoding.ASCII;
IPEndPoint hostEndPoint;
IPAddress hostAddress = System.Net.IPAd dress.Loopback;
int conPort = port;

Byte[] ByteGet = ASCII.GetBytes( "GET / HTTP/1.1\r\nHost:
127.0.0.1\r\nCo nnection: Close\r\n\r\n") ;
byte[] RecvBytes = new byte[256];
hostEndPoint = new IPEndPoint(host Address, conPort);
using (Socket s= new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p))
{
s.Connect(hostE ndPoint);
s.Send(ByteGet, ByteGet.Length, 0);
s.Shutdown();
// shouldn't need to call close explicitly; Dispose should handle this
// note that by using the using construct, Dispose is called.
}
</NewSnip>

The main reason you should implement IDispose in one of your own classes
is to ensure that unmanaged resources (Database connections is the
classic example) are released.
You might find this template helpful:
<ClassImplement ingDispose>
class Billy: IDisposable
{
private bool mDisposed = false;

public void doStuff()
{
// do this in each public method in case user called dispose,
// but then tried to call another method
if ( mDisposed ) throw new ObjectDisposedE xception();
// do what you normally do.
}

/// <summary>
/// If SupressFinalize wasn't there, the gc would have to do all the
/// extra work that is required for objects in the finalization queue.
/// </summary>
public void Dispose()
{
Dispose( true );
GC.SuppressFina lize(this);
}

protected virtual void Dispose( bool disposing )
{
if ( disposing )
{
// dispose any dependant managed objects if necessary.
// You don't want this to happen when the GC is calling this code
// because you have no idea what state other objects would be in at
that point.
disposed = true;
}
// Free unmanaged resources here.
}

~Billy()
{
Dispose( false );
Debug.Assert(fa lse, "You are using this object improperly. Create in
using construct or ensure to call Dispose()");
}
}
</ClassImplementi ngDispose>

André wrote:
Thanks Kevin,

Can you help me add the dispose interface?

This is my simple ping class......

Nov 17 '05 #37

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

Similar topics

1
2338
by: Bob | last post by:
Are there any known applications out there used to test the performance of the .NET garbage collector over a long period of time? Basically I need an application that creates objects, uses them, and then throws them away and then monitors the garbage collection and store statistics on it, preferably in C#. I want to know what is the longest period of time that an application may lock up while garbage collection is processing. Thanks!
6
810
by: Ganesh | last post by:
Is there a utility by microsoft (or anyone) to force garbage collection in a process without have access to the process code. regards Ganesh
11
2737
by: Rick | last post by:
Hi, My question is.. if Lisp, a 40 year old language supports garbage collection, why didn't the authors of C++ choose garbage collection for this language? Are there fundamental reasons behind this? Is it because C is generally a 'low level' language and they didn't want garbage collection to creep into C++ and ruin everything? Just wondering :)
34
6435
by: Ville Voipio | last post by:
I would need to make some high-reliability software running on Linux in an embedded system. Performance (or lack of it) is not an issue, reliability is. The piece of software is rather simple, probably a few hundred lines of code in Python. There is a need to interact with network using the socket module, and then probably a need to do something hardware- related which will get its own driver written in C.
5
3614
by: Bob lazarchik | last post by:
Hello: We are considering developing a time critical system in C#. Our tool used in Semiconductor production and we need to be able to take meaurements at precise 10.0 ms intervals( 1000 measurement exactly 10 ms apart. In the future this may decrease to 5ms ). I am concerned that if garbage collection invokes during this time it may interfere with our measurement results. I have looked over the garbage collection mechanism and see no...
8
3047
by: mike2036 | last post by:
For some reason it appears that garbage collection is releasing an object that I'm still using. The object is declared in a module and instantiated within a class that is in turn instantiated by the mainline. The class that instantiated the object in question is definitely still in existence at the point garbage collection swoops in and yanks it out from under my processing. Is there a way to ensure an instantiated object cannot be freed...
28
3189
by: Goalie_Ca | last post by:
I have been reading (or at least googling) about the potential addition of optional garbage collection to C++0x. There are numerous myths and whatnot with very little detailed information. Will this work be library based or language based and will it be based on that of managed C++? Then of course there are the finer technical questions raised (especially due to pointer abuse). Is a GC for C++ just a pipe dream or is there a lot of work...
56
3716
by: Johnny E. Jensen | last post by:
Hellow I'am not sure what to think about the Garbage Collector. I have a Class OutlookObject, It have two private variables. Private Microsoft.Office.Interop.Outlook.Application _Application = null; Private Microsoft.Office.Interop.Outlook.NameSpace _Namespace = null; The Constructor: public OutlookObject()
350
11907
by: Lloyd Bonafide | last post by:
I followed a link to James Kanze's web site in another thread and was surprised to read this comment by a link to a GC: "I can't imagine writing C++ without it" How many of you c.l.c++'ers use one, and in what percentage of your projects is one used? I have never used one in personal or professional C++ programming. Am I a holdover to days gone by?
158
7909
by: pushpakulkar | last post by:
Hi all, Is garbage collection possible in C++. It doesn't come as part of language support. Is there any specific reason for the same due to the way the language is designed. Or it is discouraged due to some specific reason. If someone can give inputs on the same, it will be of great help. Regards, Pushpa
0
9680
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
10455
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
10006
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
9052
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7547
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5441
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
5573
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2925
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.