An infinite loop is OK, if it doesn't uses all the CPU for nothing, and is used in an application (or a thread) that only does one task (such as a Windows service or a specific background thread that read/writes to a queue).
For the specific case of the message queue reading, I would suggest using MessageQueue.Receive
that accepts a timeout as parameter. It's a blocking call (until a message is available in the queue OR the timeout is reached) that won't consume the CPU. You will have to catch the exception that'll be thrown when the timeout is reached.
Example:
MessageQueue messageQueue = ...;
TimeSpan queueReceiveTimeout = ...;
while (true)
{
try
{
Message message = messageQueue.Receive(queueReceiveTimeout);
...
}
catch (MessageQueueException msmqEx)
{
if (msmqEx.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
{
// Exception handling exceptionally used for normal code flow
// Swallow the exception here
}
else
{
throw;
}
}
}
You could then use a condition in the while
to stop your service properly (example: while (!this.isServiceStopping)
) with a relatively small timeout (for example 5s), so your service/thread can be stopped properly within a maximum of 5 seconds.