Right now, I’m reading outside application’s memory in a new thread with a infinte loop
public void ReadMemory()
{
//read memory
Thread.Sleep(10);
}
Unfortunately, with even sleep of 1 ms, I can get 60-100 loops during 1 minute. Without any sleep, it’s 1000-1500/sec loops but it takes much CPU. I can’t believe there’s nothing I can do with that so Im asking you here :P. CPU usage might be a problem because I’d like to add few more background-working functions in a different threads(or smth else)
is there anything that doesn’t decrease ammount of loops like that with a pause of 10 ms?
Don’t worry about CPU usage. It’s a nonsensical concept.
There’s no such thing as “code that runs a little bit”, or “running code slowly to only consume 25% CPU”.
At the lowest level, it’s a binary thing: your code either runs, consuming 100% of the core it runs on, or it doesn’t, in which case it uses 0% CPU.
The CPU usage that the OS shows you is a running average.
So the question you need to ask is not “how do I run my code without using so much CPU”, but the much simpler “does my code run when it shouldn’t be running?” If you want your code to run, then it will, temporarily, at least, use 100% CPU, and there’s nothing wrong with that.
It’s not really clear what role the
Sleep()call plays in your application.What are you waiting for? Do you just want a few milliseconds to pass between each iteration? Or are you waiting for some specific event to occur?
In any case, when you call
Sleep(10), you are not suspending your thread for 10 milliseconds. You are suspending it for at least 10 milliseconds. You’re telling the OS to put the thread into a sleep queue now, and once 10 ms have passed, the thread should be considered eligible to execute again. But that still depends on the OS getting around to scheduling your thread, which might take another 10ms (or more, or less, depending on a variety of factors)On Windows,
Sleep(0)is a special case, which you could experiment with. Instead of actually suspending your thread, it simply tells the OS that the thread is done with its current timeslice, allowing other threads/processes to execute, but without putting your thread to sleep: it’s still eligible to be scheduled the next time a context switch occurs.So if the goal is simply to ensure that other threads/processes get a chance to run, calling
Sleep(0)might be a way to do it.Another way is just to ignore the issue, and trust that the OS knows how to schedule processes (that is a pretty safe assumption. Don’t worry about this unless you’ve actually seen that your other background processes are being starved. They most likely won’t be).
And finally, of course, you can set thread and process priority, hinting to the OS at which threads it should prefer to schedule. If you give this thread a low priority, it will only be scheduled when no higher-prioritized thread is available, ensuring you won’t starve out other threads.