Waiting, it isn’t as simple as twiddling your thumbs

time to read 3 min | 523 words

Just thought that it would be interesting post to talk about the evolution of a single method. This is used solely for the integration tests, by the way.

public void WaitForAllMessages()
{ 
  while (mailBox.IsEmpty == false)
  {
    Thread.Sleep(100);
  }
}

It started its life very simply, as just a method that waited until the mailbox was empty. But then we run into a problem, sometimes the method returned while a message was being processed, and that caused the tests to fail.

Then we had this:

public void WaitForAllMessages()
{ 
  while (mailBox.IsEmpty == false  || currentlyProcessingMessages > 0)
  {
    Thread.Sleep(100);
  }
}

There are other pieces of the code, that update the currentlyProcessingMessages piece, but it isn’t really interesting. Some time passed, and we run into additional issues, which led to this beast:

public void WaitForAllMessages()
{
    // we wait in case there are additional messages that have not yet arrived
    // to the listner. We arbitrarily define that if we wait for 5 consecutive 
    // times with no new messages, there are no more messages
    int countOfTimesTriesToWaitAndThereWereNoMessages = 0;
    while(countOfTimesTriesToWaitAndThereWereNoMessages < 5)
    {
          if (WaitForAllMessagesInMemoryQueueOrProcessing())
            countOfTimesTriesToWaitAndThereWereNoMessages = 0;
        else
              countOfTimesTriesToWaitAndThereWereNoMessages += 1;
          Thread.Sleep(100);
    }
}

private bool WaitForAllMessagesInMemoryQueueOrProcessing()
{
    bool waited = false;
    while (mailBox.IsEmpty == false ||
           currentlyProcessingMessages > 0)
    {
        waited = true;
        Thread.Sleep(100);
    }
    return waited;
}

And that is where we are now.