Skip to main content
gamedev.net
🔒 Locked

[.net] Deleting Objects

Started by Pipo DeClown Jun 29, 2004 at 7:04 AM 5 replies 1.5k views
Original Post
Pipo DeClown
Pipo DeClown
I have this timer, that I want to be able to stop, and then nullify. Should I just call .Stop() and then =null? Or should I do something with .Dispose()? Anythin else I need to do?
JDuke
JDuke
Technically, you could probably just call Stop, because MSDN says "A timer that is disabled is subject to garbage collection."

However, what I've read is that whenever any object implements the IDisposable interface, you are supposed to always call Dispose yourself, even if you know it doesn't do anything. For example, if you call Close on a SqlConnection, then Dispose doesn't do anything, but there's no guarantee that it won't eventually do something, so you should call it. I've also read that setting an object to null actually can affect when the GC will free the object, but it's not worth the trouble unless you have large objects.

This blog has links to both of these questions and more:
http://www.moskalyuk.com/blog/archives/000046.html

I don't know how accurate those articles are, but since reading them I've at least been trying to make sure I call Dispose (or use the using statement) for my disposable objects.

So, since Timer inherits from Component (and therefore, IDisposable) then I guess you should at least call Dispose, and according to the above article, setting the object to null couldn't hurt either. Plus, setting it to null would keep you from accidentally using the disposed object later in your code.
Pipo DeClown
Pipo DeClown
Thanks! I dunno cuz I Stop()ed Dispose()d and =null;ed, but then an exception came out (just once, all the other 1000 builds went ok). Now I removed Dispose(). Let's see what happens..
JMOmandown
JMOmandown
Yeah, garbage collection will do it for you, also just as a side note, if you redeclare it then the old version if it hasn't already will be deleted
Toolmaker
Toolmaker
On a side note, why would you want to dispose yourself of the timer before the form gets disposed? When you're done with it, either Stop() it or set it to Enabled = false; I use 2 times in my form, and once I am disposing the form, I dispose the timers too.

Toolmaker
 
Pipo DeClown
Pipo DeClown
Because I want to check if it's null.

Pseudo Loop

if( Timer == null )
{
}

Timer = new Timer();
Timer....
Timer = null;
JMOmandown
JMOmandown
you know its possible to just check and see if it is and make it equal to null while its still running you don't have to stop it to do so

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.