user2080185
user2080185

Reputation: 101

GC.KeepAlive() and System.Timers.Timer

I have declered System.Timers.Timer object in class level and created in constructor.started the timer in another method.

In elapsed event handler enabled property set to false and excute some code and again enabled set to true.

I am getting elapsed events for each intervel. problem is aftre some time elapsed is stoped.

I am suspecting that timer object is collected by the GC at the momment enabled property set to false in the elapsed event hanler eventhadler.

So I want my timer object set to keep alive.

Where should i declare GC.KeepAlive(timer) in my project?

Upvotes: 2

Views: 2381

Answers (1)

Jim Mischel
Jim Mischel

Reputation: 133995

If the timer is declared at class level, it's not being collected automatically by the GC, because it doesn't go out of scope. And setting Enabled to false can't cause the behavior that you describe. Your problem is somewhere else.

I would suspect an exception in your event handler. System.Timers.Timer swallows exceptions that occur in the event handler, meaning that if an exception escapes the event handler, you'll never know about it.

I suspect your code is written similar to this:

myTimer.Enabled = false;
// do stuff here
myTimer.Enabled = true;

If an exception is thrown during the "do stuff here", the exception escapes the handler, the timer never gets re-enabled, and the timer code swallows the exception so you never know that something happened.

You should write your event handler like this:

myTimer.Enabled = false;
try
{
    // do stuff here
}
catch (Exception ex)
{
    // handle exceptions
}
finally
{
    myTimer.Enabled = true;
}

You normally want to catch just specific exceptions--the ones you know how to handle. Catching all exceptions like above is generally bad practice.

Upvotes: 5

Related Questions