Reputation: 1212
A common pattern I've seen (and have used myself) in order to keep a thread from hogging CPU time while processing data in a loop looks something like this:
foreach (itemInACollection)
{
// do some processing on the item
// ...
// ...
Thread.Sleep(1);
}
I don't particularly like this solution and would like to find a better way of accomplishing the same thing.
My question is two-fold, the first dealing with an existing code base that does not lend itself to much alteration and the second dealing with architecting a new solution.
*Note: I realize that different data types may have different solutions more suitable to their implementation (and container types), but I was wondering if there might be a better pattern for processing a collection (e.g. array) of objects.
Upvotes: 1
Views: 485
Reputation: 273179
Why shouldn't your thread hog the CPU in the first place?
A thread is a (memory) costly object, run it flat out and then abandon it.
Managing system resources is not really the responsibility of your item-processing code.
When you do have a performance problem the management of this should be shifted to the code calling this.
When simply processing independent items, Parallel.ForEach might be a good choice. Why hog just 1 CPU when you can use all of them.
Upvotes: 2
Reputation: 182753
If you have a bunch of work to do, you should just do it. This doesn't typically create any problems so there's typically nothing to solve.
Upvotes: 1
Reputation: 294187
The question is quite broad. I'll give you some pointers:
Understand where CPU consumption comes from. Overwhelmingly will be cache miss and memory access cost, not instructions executed. See CPU Caches and Why You Care - Scott Meyers
Cap the process available resources. Use a Job Object, set a CPU limit and then start the process in this job. This will be enforced by OS and the process cannot exceed the set limits (its thread will simply not be scheduled by the OS). A poor man equivalent is start /low
.
Read this series: Designing Applications for High Performance, Part 2 and Part 3.
Learn to profile apps to identify bottlenecks: Beginners Guide to Performance Profiling.
Upvotes: 1