Danish
Danish

Reputation: 59

Infinite looping consumes 100% CPU

I am stuck in a situation where I need to generate a defined frequency of some Hz. I have tried multimedia timers and all other stuff available on the internet but so far an infinite loop with some if-else conditions gave me the best results. But the problem in this approach is that it consumes almost all of the cpu leaving no space for other applications to work properly.

I need an algorithm with either generates frequency of some Hz to KHz.

I am using windows plateform with C#.

Upvotes: 3

Views: 1060

Answers (4)

Zdeslav Vojkovic
Zdeslav Vojkovic

Reputation: 14591

You can't accurately generate a signal of a fixed frequency on a non-realtime platform. At any moment, a high priority thread from same or other process could block the execution of your thread. E.g. when GC thread kicks in, worker threads will be suspended.

That being said, what is the jitter you are allowed to have and what is the highest frequency you need to support?

Upvotes: 3

Joh
Joh

Reputation: 2370

The way I would approach the problem would be to generate a "sound wave" and output in on the sound card. There are ways to access your sound card from C#, e.g. using XNA. As others have pointed out, using the CPU for that isn't a good approach.

Upvotes: 2

loopedcode
loopedcode

Reputation: 4893

As you are generating a timer, You would want to Sleep based on the period of your frequency.

You will have to run your frequency generator in its own thread and call

Thread.Sleep(yourFrequencyPeriodMs);

in each iteration of period.

Upvotes: 0

burning_LEGION
burning_LEGION

Reputation: 13460

Use Thread.Sleep(delay); in your loop

it's reduce processor usage

Upvotes: 0

Related Questions