Link to home
Start Free TrialLog in
Avatar of JAMES
JAMES

asked on

Why is my thread.sleep loop behaving strangely

Hi,

I have this loop in a class which is executed on a new background thread from my main UI :-

public bool WaitForWindow(string strClass, string strCaption, int iMaxSeconds, int iSet)
{
      i = iSet;
      if (i < iMaxSeconds * 2)
      {
            if (!GetWindow(strClass, strCaption,0))
            {
                  i++;
                  Thread.Sleep(500);
                  WaitForWindow(strClass, strCaption, iMaxSeconds, i);
            }
            return true;
      }
      else
      {
            return false;
      }
}

What I am trying to achieve is for my loop not to be indefinately looping so I test how many times it's looped * delay which relates roughly to the number of seconds I would like to keep testing for (iMaxSeconds).

The loop seems to perform find and the "return false" line is hit when the condition is not met within the time allowed but then the very next line it executes is back up to the "return true" even if the condition is not met.

eg. having stepped through the code with a iMaxSeconds set to 2 (ie loop 4 times) the final running order seems to be :-

return false
return true
return true
return true
return true

!!!! - Any ideas why these four "return true" lines are being executed??

Many thanks.

James.
ASKER CERTIFIED SOLUTION
Avatar of andrewjb
andrewjb
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
oops.

Add

Thread.Sleep(500) before the iteration++

Avatar of JAMES
JAMES

ASKER

Im an idiot!

Sometimes you just can't see the wood for the trees!

Many thanks.

James.