Systereading.Timer class question

R

R.A.

The follwowing remarks taken from the MSDN:

As long as you are using a Timer, you must keep a reference to it. As with
any managed object, a Timer is subject to garbage collection when there are
no references to it. The fact that a Timer is still active does not prevent
it from being collected.

What does this mean?
If I have the following:

class Sample1 : System
{
DataTable dt = new DataTable ();

public process ()
{
while (true)
{

do something
}
}

}

can the dt be delete by the garbage collection?
 
M

Mattias Sjögren

The follwowing remarks taken from the MSDN:

As long as you are using a Timer, you must keep a reference to it. As with
any managed object, a Timer is subject to garbage collection when there are
no references to it. The fact that a Timer is still active does not prevent
it from being collected.

What does this mean?

It means exactly what it says. If you for example do

void StartATimer()
{
Timer t = new Timer(new TimerCallback(Handler), null, 0, 1000);
}

the timer will eventually be garbage collected and stop calling
Handler, since you don't hold a reference to the object after the
StartATimer method returns.


If I have the following:

class Sample1 : System
{
DataTable dt = new DataTable ();

public process ()
{
while (true)
{

do something
}
}

}

can the dt be delete by the garbage collection?

Not before the Sample1 object itself is eligible for garbage
collection.



Mattias
 
B

Bob Grommes

Any managed object is subject to data collection when there are no more
references to it. In your example, the dt member will be garbage collected
at some point after there are no more references to the runtime instance of
Sample1 (unless you have a method of Sample1 that returns a copy of the dt
reference to something outside the class, in which case there might be other
references that would keep it from being garbage-collected even if the
Sample1 instance is destroyed).

--Bob
 
S

Sunny

Hi,
what does that mean is:

public void MyMethod()
{
if (somecond)
{
Timer t = new Timer(new TimerCallback(Handler), null, 0, 100);
}

while (something)
{ do something}
}

The reference to the timer object t goes out of scope when you exit the
"if" block. So there is no more references to that timer, and it willl
be garbage colected at some point of time, even if it is still running.

Sunny
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top