RiaanDP
RiaanDP

Reputation: 1212

Using Thread.Sleep to keep thread from hogging CPU

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.

  1. Is there another way to prevent a thread from hogging the CPU when processing data in the way in the example above (i.e. when using a loop and iterating over each item)?
  2. I realize that without providing more information the above example is quite broad, but are there other patterns that provide a better way of processing (synchronously) a large collection of data in a background thread?*

*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

Answers (3)

Henk Holterman
Henk Holterman

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

David Schwartz
David Schwartz

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

Remus Rusanu
Remus Rusanu

Reputation: 294187

The question is quite broad. I'll give you some pointers:

Upvotes: 1

Related Questions