Thursday, March 17, 2005

Variable scope and Debug vs. Release builds

Lately, I was debugging some code when I came across this little gem in global.asax.cs:


protected void Application_Start(Object sender, EventArgs e)
{
StartTimer();
}

public void StartTimer()
{
string METHODNAME = "StartTimer";

try
{
TimerCallback tcallback = new TimerCallback(TimerMethod);

Timer timer = new Timer(tcallback, null, new TimeSpan(0, 0, 1), new TimeSpan(0, 0, 10));
}
catch (Exception ex)
{
System.Diagnostics.Debug(ex.Message);
}
}

The code basically starts a timer when the web application starts (when the first web page request is issued by a client). The timer fired fine during debugging, but when I ran the web app without debugging, the timer didn't fire. I did fix the issue by scoping the timer object at the Global class level, rather than as a local variable within the StartTimer() mehtod (the timer object was only visible in StartTimer), but I wanted to find out why the debug build exhibited different behavior from the Release build. I stumbled across Mike Tautly's weblog On Garbage Collection, Scope and Object Lifetimes and he describes one reason for the issue: The JIT optimization will determine how long local variables are kept around before being garbage collected.

Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?