473,796 Members | 2,444 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
That's okay. Let it be.

If KeepAlive holds a class level reference to the Socket then KeepAlive
would be a candidate for implementing IDisposable. More specifically,
if the same Socket instance were used across different method calls on
KeepAlive then it would be imperative to implement IDisposable.

André wrote:
I still notice that the memory usage is getting higher each time the pingis
created. I know that the Garbage collection will get to it when it does.
Should I call the GC.collect? or just let it be?

Also, when is a time that I should use the IDisposable interface? I'm still
new to GC

Thanks
"Brian Gideon" wrote:
Yes, that's fine. Except, you really don't need to set the object
reference to null.

André wrote:
ok, i've made the change. Do i just leave this code as it stands?

private void timer_Elapsed(o bject sender, System.Timers.E lapsedEventArgs e)
{

KeepAlive keep = new KeepAlive(Conve rt.ToInt32(Loca lPort));
keep.ping();
keep = null;
}



Nov 17 '05 #11
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?
Nov 17 '05 #12

"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.

Willy.
Nov 17 '05 #13
then why there is something like Dispose(bool disposing) ????
Nov 17 '05 #14
Yes, it will be disposed. Eventually.

Why bother with calling Dispose? I think your original post answered THAT
question.

Look, you're already using a try/catch block. Add a finally block and
dispose that sucker. It's as easy as that. If you really want to know all
the technical details, download the FREE Microsoft .Net SDK:

http://www.microsoft.com/downloads/d...displaylang=en

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Ambiguity has a certain quality to it.

"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?

Nov 17 '05 #15
On Wed, 19 Oct 2005 09:17:27 +0300, "The Crow" <q> wrote:
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 doesn't have anything to do with garbage collection. The
garbage collector basically has the following functionality:

1) Find objects that are eligible for garbage collection.
2) If the object has a finalizer, run it.
3) Mark the memory the object used as availible.

The problem with garbage collectors is that they aren't deterministic.
It could very well be 10 minutes or longer between the time that an
object is eligible for collection and the time that it is actually
collected.

This can be a problem when dealing with resources that can't wait
around for the garbage collector to run. The most common example being
operating system handles of different kinds. In those cases the
programmer manually has to tell the object to dispose of the resource,
which is the reason why the Disposable pattern exists.

Here is an example:

using System;
using System.IO;

class Test
{
string name = "test.txt";

// Safe write that disposes of the StreamWriter object
public static void WriteSafe()
{
//Note: the using construct will automatically call Dispose on
// the StreamWriter object when in leaves the scope.
using(StreamWri ter sw = new StreamWriter(na me))
{
sw.Write("Test" );
}
}

// Write which doesn't dispose of the StreamWriter object
public static void WriteUnsafe()
{
StreamWriter sw = new StreamWriter(na me);
sw.Write("Test" );
}

public static void Main()
{
WriteSafe();
//The file test.txt has been closed by the Dispose() method
WriteUnsafe();
//The file test.txt is open
Gc.Collect();
//The file test.txt has been closed by the StreamWriter
//finalizer (which most likely called the Dispose() method)
WriteUnsafe();
//The file test.txt is open
WriteUnsafe(); //This method call throws an exception, because the
//file is already open.
}
}

--
Marcus Andrén
Nov 17 '05 #16
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 #17
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?

--
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 #18

"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?


Yes, this is what I want to stress, while it's true that the Finalizer
thread kicks in on request of a GC run, there no strong guarantee that your
Finalize (that calls your Dispose(bool)) method will execute at the next
Finalizer run, there are (very rare) cases in which your Finalizer might
never be called at all. That said, when you expect deterministic disposal of
your unmanaged resources, you need an explicit call to Dispose (or use the
using statement for fine grained scopes), relying on the Finalizer offers
you non-deterministic disposals.
Willy.
Nov 17 '05 #19
I believe those rare cases where the finalizer doesn't run at all can
be mitigated with the new constrained execution regions technology in
version 2. It is an interesting addition to the framework.

Brian

Willy Denoyette [MVP] wrote:
Yes, this is what I want to stress, while it's true that the Finalizer
thread kicks in on request of a GC run, there no strong guarantee that your
Finalize (that calls your Dispose(bool)) method will execute at the next
Finalizer run, there are (very rare) cases in which your Finalizer might
never be called at all. That said, when you expect deterministic disposal of
your unmanaged resources, you need an explicit call to Dispose (or use the
using statement for fine grained scopes), relying on the Finalizer offers
you non-deterministic disposals.
Willy.


Nov 17 '05 #20

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
10228
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
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
6788
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
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?
1
4116
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
2
3731
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.