Nasty Bugs!

I was trying to troubleshoot an issue that is related to wrong timing. I found two bugs in the following code. Who is up for a challenge finding them?
To make it easy I included the lines that have the bugs

 
 public static bool poll(int param1, int microSeconds)
 {
 long timeout = DateTime.Now.Ticks + microSeconds*10;
while(true)
{
    
                  if (DateTime.Now.Ticks > timeout & microSeconds > 0)
                        {
                            return false;
                            //break;
                       }
if (DataReady() == true)
   return true;
}
}

microseconds*10 is not a conversion to ticks, so your timeout is going to happen really fast!

The single ampersand should be two ampersands. Also some additional parentheses would help clarify what the logic should be.

It is also safer to use a system constant, i.e. TimeSpan.TicksPerMillisecond (adjust for microseconds), instead of hard coded value.

This code should have Thread.Sleep(1) in it! Let the other threads while polling :slight_smile:

@ ransomhall: 1 tick = 100nanosec
Do you have a different answer for this?

You were right with the other one.

well, assuming that math gets you the timeout you want, I suppose microSeconds should be a long, not an int.

something like

long timeout = DateTime.Now.Ticks + ((long)microSeconds*10);

In our case it is int. Where is the problem? :wink:

OK let me get closer:
microSeconds is 300,000,000

max int is 2,147,483,647, so 300,000,000*10 goes kerplewy, kapow… to use technical terms.

Here is the problem:
microSeconds is 300,000,000

This gave a worng value


long timeout = DateTime.Now.Ticks + microSeconds*10;

This fixed the issue:


long timeout = DateTime.Now.Ticks +((long)microSeconds)*10;

what’s with the underscore after microSeconds?

Ooops it should ne “)”. I fixed it.

Now theother question is:
Is it possible to ask Visual studio to raise warnings when similar issues are there?

There a few tools that let you add your own custom rule sets, like FxCop. I’m not entirely sure that you could warn on this exact problem. A unit test would expose this.