Timer not accessed

I have code like this:

using System;
using System.Threading;
public static class SessionManager
{
private static readonly Timer CheckTimer;
static SessionManager()
{
CheckTimer = new Timer(HandleTimerTick, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5));
}
private static void HandleTimerTick(object sender)
{
// Do Stuff
}
}

Resharper is saying that CheckTimer is assignd to but never used. Well, sure but in this case it's correct?

I kind of thought I had to have a field to have the timer stay in scope. I haven't tried it (maybe I will now i've thought of it) but wouuld this work?

using System;
using System.Threading;
public static class SessionManager
{
static SessionManager()
{
new Timer(HandleTimerTick, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5));
}
private static void HandleTimerTick(object sender)
{
// Do Stuff
}
}

Looks wierd :)

Thanks
Mark

2 comments
Comment actions Permalink

You do need the field. Without it, the GC will eventually collect the Timer object, which will cause the finalizer of the internal TimerBase object to delete the timer.

0
Comment actions Permalink

Thanks Richard, that's what I thought - nice to have it confirmed.

0

Please sign in to leave a comment.