Sometimes the need arises to wait for a condition or property to become true, this is especially useful for unit / integration tests. The System.Threading namespace contains SpinWait which will enable use to enter a condition that we want to wait on to see if it becomes true.

In the code example below, we have a property called recevied inside the the object sc (a socket wrapper). This socket client waits for the response from the server, but only for 30 seconds. So, we need to wait for the response or stop waiting after the timeout. I used to do it with bad code, causing a lot of work for the CPU, increasing its usage a lot.

The bad code was:

while ((!sc.received) && (endTime > dt))
{
    dt = DateTime.Now;
}

Don’t use the code above!!

The right code use the special function SpinUntil, in this way:

SpinWait.SpinUntil(() => sc.received, timeoutSec * 1000);

The 2 snippet do the same actions, but the second one it’s the right thing for the CPU.

You can also do it without a timeout, but in this way you can enter in an infinite wait.

Advertisements