Destroy a Timer object in its callback method

C

Curious

Hi,

I have a timer object that's launched as below:

mTimer = new System.Threading.Timer (new
TimerCallBack(SubscribeTrade), null, 15000, 15000);

void SubscribeTrade (object state)
{
DateTime now = DateTime.Now;
TimeSpan elapsed = now.Subtract(mStartTime);
int minutes = elapsed.Minutes;

if (minutes <= 30)
{
//Code omitted here
}
else // Need to destroy the timer after 30 minutes here
{
// Is this the right way to destroy the timer object?
mTimer.Dispose();
}
}

As shown in my code, I need to destroy the timer after it's run for 30
minutes. Will it cause a problem if I dispose the timer inside its
callback method, "SubscribeTrade"?

If it will, how can I destroy it in 30 minutes?
 
C

Cor Ligthert[MVP]

Curious,

I don't like system.threading.timers as it is working even as the thread has
stopped.

However, what do you mean with destroy, disable it?

Be aware that dispose is not a kind of command to finalize things. Dispose
is a method inherited from component which is in almost 20% of every class
(as Jon once wrote) which you can use to overload to release non manages
resources.

Cor
 
C

Curious

Curious,

I don't like system.threading.timers as it is working even as the thread has
stopped.

However, what do you mean with destroy, disable it?

I mean to disable it. Having a timer run periodically is a waste of
resources even when it does nothing. I actually want to free the
memory occupied by the timer. However, I care less about the memory
than stopping the timer from running.

Any advice?
 
J

Jack Jackson

I mean to disable it. Having a timer run periodically is a waste of
resources even when it does nothing. I actually want to free the
memory occupied by the timer. However, I care less about the memory
than stopping the timer from running.

Any advice?

You can stop it using the Change() method:
<http://msdn.microsoft.com/en-us/library/yz1c7148.aspx>.

This code <http://msdn.microsoft.com/en-us/library/ms149618.aspx>
shows calling Dispose() from the callback method, so unless the
documentation lies it is OK to do so.
 
C

Curious

Thanks Jack! I'll give it a try to call

mTimer.Dispose();

from the callback method to destroy the mTimer entirely.
 

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