System.Threading.Timer improper function in Release mode

H

Hagay Lupesko

Hi,

I've encountered a strange phenomena which appears to me as a bug:

I have an engine that uses a System.Threading.Timer to invoke a delegate
every X minutes.

The code looks something like this:
TimerCallback callBack = new TimerCallback(Run); // run is obviously a
method
analysisTimer = new Timer(callBack, null, 0, delay);
Console.ReadLine();

Everything works just fine when the code is build in Debug mode, but when
the code is build in Release mode the delegate is invoked once only.

After creating debug symbols for the Release mode it looks like the timer
class is optimized away...

The workaround solution I used was declaring the timer as static.

But obviously it's not very nice...

Any clue as to is this a bug, or what's wrong with the code ?

Thanks, Hagay.
 
V

Vijaye Raji

You say that the Run method is called once in release mode. If it was
optimized away, it shouldn't be called even once.

It's hard to tell why the code was optimized away from the snippet you
provided. Is this a console/windows app? If Console, what is your current
thread doing? What is the code inside the Run method?

-vJ
 
H

Hagay Lupesko

Hi vj,

I can say the timer was optimized away pretty certainly, because when
building the app in release mode with optimization switch turned off, the
app ran as required.

Anyway, in response to your question, it's a console app, and as you cann
see in the code the current thread is blocking on Console.Readline() .

Hagay.
 
J

Jon Skeet [C# MVP]

Hagay Lupesko said:
I can say the timer was optimized away pretty certainly, because when
building the app in release mode with optimization switch turned off, the
app ran as required.

Anyway, in response to your question, it's a console app, and as you cann
see in the code the current thread is blocking on Console.Readline() .

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
 
V

Vijaye Raji

I wrote a tiny app as below and I can't repro the problem. Do you see any
differences between this app and the one you have?

class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
System.Threading.Timer t = new System.Threading.Timer(
new System.Threading.TimerCallback(OnTimer), null, 0, 1000);
Console.ReadLine();
}

static void OnTimer(object obj)
{
Console.WriteLine("Yes");
}
}
 

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