Ask the Expert

My Windows Service text file is hogging my CPU

I am trying to create a Windows Service that will read each row of a text file and insert them into a SQL database. The text file can have a max of 150,000 rows. When I try to read one line from the text file, insert into the database and reiterate up to the max, the CPU maxes out. This service needs to run in the background using as little processor power as possible. Do you have any ideas on how to accomplish this? Thanks for your time.
The problem is that you're not playing nice with the CPU. When your program goes into that tight loop reading the lines, the thread scheduler sees you're not waiting on anything from the OS and will continually schedule the thread. What I would do is the following:
  1. Call SetTimer and tell the API to call back one of your functions. I'd set the elapsed time to something like 750 milliseconds or even a second.
  2. In your timer function, I'd read three to five lines and insert those lines into the database before ending.

By using the timer, you'll break up the processing and thus ensure you're not hogging the CPU.

This was first published in February 2003

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: