问题
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#.
回答1:
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?
回答2:
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.
回答3:
Use Thread.Sleep(delay);
in your loop
it's reduce processor usage
回答4:
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.
来源:https://stackoverflow.com/questions/12729075/infinite-looping-consumes-100-cpu