Using C#, I want to generate 1,000,000 files from DB, each record in separate file.
What is the best way to generate this files in minimum time?
Here is my code without threading :
AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit); // to calculate the execution time in case of using threading
SqlCommand cmd = new SqlCommand(@"select top 1000000 p1+','+p2+','+p3+','+p4 as line from lines ", con);
con.Open();
var rdr = cmd.ExecuteReader();
int i = 0;
while (rdr.Read())
{
string line = rdr.Getring(0);
string filename = String.Format("file{0}.txt", ++i);
File.WriteAllText(filename, line);
}
rdr.Close();
con.Close();
Since your operations are IO bound and not CPU bound, the best way is to have 2 threads, one that reads from DB the records and put it into a queue, the other read from the queue and generate the files.
Alternatively, you can use the CLR thread pool for that, something like
and writeData would look like
The disadvantage of using the ThreadPool is you could end up more threads than you want, since your threads will be blocked in IO most of the time, the thread pool will create new threads to service your requests.
You can try the thread pool first and measure the performance, if you are not satisfied, you can try the 2 threads, 1 queue approach; well known as Producer/Consumer problem.