Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 242
  • Last Modified:

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.
0
JAMES
Asked:
JAMES
  • 2
1 Solution
 
andrewjbCommented:
Errr... because you're calling the function recursively rather than looping round until the time expires...?

Should be:

(NB you don't need iSet as a parameter!)

public bool WaitForWindow(string strClass, string strCaption, int iMaxSeconds)
{
  int iterationCount = iMaxSeconds * 2;

  int iteration = 0;

  while ( iteration < iterationCount )
  {
    if ( GetWindow(strClass , strCaption , 0 ) )
      return true;

    iteration++
  }

return false;
}
0
 
andrewjbCommented:
oops.

Add

Thread.Sleep(500) before the iteration++

0
 
JAMESAuthor Commented:
Im an idiot!

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

Many thanks.

James.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now