Exiting Loops Using Timeouts

Problem
On certain occasions, a test’s execution should only continue after a certain event. You’re using a looping construct to check for a condition, and you want to know what to do when it has been met.

Solution
Use timeouts to avoid infinite loops.

Comments
You may want to implement global timeouts in your project to reduce maintenance.

Example

// Method that checks the existence of a file.
bool FileExists() {
    ...
}

// Decrease timeout by 1 and wait for a second with each iteration.
// After 10 seconds, break out of the loop.
var maxWaitTime = 10;
while (!FileExists()) {
    if (maxWaitTime == 0) {
        break;
    }
    maxWaitTime--;
    Thread.Sleep(1000);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s