How not to use Async function calls
The following is a piece of code I recently ran into:
IAsyncResult asyncResult = m_Queue.BeginPeek();
while (!asyncResult.IsCompleted && m_Running)
Thread.Sleep(10);
if (m_Running)
{
Message message = m_Queue.EndPeek(asyncResult);
ProcessMessage(message);
}
Now this is already running in a background thread, not that it makes a lot of difference though. But calling an async begin function, then sleeping until it is finished and retrieving the result makes no sense whosoever. You might as well just call the regular Peek() and be done with it.
So the rational behind writing it this way? Well Peek raises and exception if there is no message in the queue and exceptions are expensive so the developer wanted to avoid them at all cost, even in a background thread. Not exactly my idea of clean and readable code. The guilty know who they are :-(