I have a strange situation with my web service.
It is a simple one – it creates a Thread that runs constantly, doing some disk checks in the background, and for every File.Exists that it performs, it goes into Sleep(10) so it doesn’t consume ALL of the CPU core.
It all works well, until I log of from RDP. When I do that, this thread will spike and consume as much as it can.
Here, have a look-see…
I have two cores, and my foreground app is using about 18% CPU (whis is shown on the NOW-meter). To the left is the CPU usage when no-one is logged on.
What is going on? And more – what to do to throttle the Thread appropriately under this circumstance?

My code snippet that produces the issue:
foreach (string fi in files)
{
if (_shouldStop)
{
break;
}
lock (_workItems)
{
StatusString = string.Format("Examining file Dir={0}\nmask={1}\nfile={2}\nqueue={3}",
root, mask, fi, _workItems.Count);
}
lock (_workItems)
{
if (!_workItems.Contains(fi))
{
if (!File.Exists(TargetForFile(fi + ".hash")))
{
StatusString = string.Format("Adding file Dir={0}\nmask={1}\nfile={2}\nqueue={3}",
root, mask, fi, _workItems.Count);
_workItems.Add(fi);
}
}
}
Thread.Sleep(10);
}
Small update:
Even Sleep(1000) does NOTHING when code is run as windows service and no-one is connected to the machine. I officially declare it a WTF.
Sleep 10 is only 10 milliseconds — so you are really close to just yielding and going back to work.
My guess would be that when you are logged on, there is enough going on that your thread doesn’t get rescheduled immediately, so that it really ends up being inactive for more than 10 milliseconds (and I think I read that the max resolution of the sleep is 100 mills, btw). However, when you are not RDP’d, the thread becomes available for rescheduling far more frequently, so it burns more CPU.
To test, try increasing your sleep duration to 500 (0.5 sec), or 1000, or so, to give you a noticeable sleep period.
Another test, would be to throw down another thread in a do-nothing loop and see if your file.exists thread yields respectfully when you are forcing the CPU to be busy.