Main Site Documentation

Nasty Bugs!


#1

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;
}
}


#2

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.


#3

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


#4

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


#5

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

You were right with the other one.


#6

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);

#7

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

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


#8

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


#9

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;


#10

what’s with the underscore after microSeconds?


#11

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


#12

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


#13

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.