I am trying to run a console process against each country. All the countries are in a datatable. Since the process for each country took 3-4 days. I have decided to run 4 countries at the same time to consume all 4 four processor of my quad core machine.
I write the above code, but the problem with this code is, it runs all the thread at the same time. I want a maximum of 4 thread simultaneously and the rest wait for their turn. I don’t mind if the application stuck in country loop and wait for the threads to be finished and start next thread immediately.
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable("Countries");
#region DataProcessing
DataColumn dc1 = new DataColumn();
dc1.DataType = System.Type.GetType("System.Int32");
dc1.ColumnName = "CountryID";
DataColumn dc2 = new DataColumn();
dc2.DataType = System.Type.GetType("System.String");
dc2.ColumnName = "CountryName";
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
DataRow dr = dt.NewRow();
dr["CountryID"] = 1;
dr["CountryName"] = "US";
dt.Rows.Add(dr);
//similar code...
dr = dt.NewRow();
dr["CountryID"] = 20;
dr["CountryName"] = "KR";
dt.Rows.Add(dr);
#endregion
ThreadPool.SetMaxThreads(5, 5);
foreach (DataRow drLoop in dt.Rows)
{
Thread job = new Thread(new ParameterizedThreadStart(ThreadJob), 5);
job.Start(drLoop["CountryName"].ToString());
}
}
static void ThreadJob(Object country)
{
//Do Something
MessageBox.Show(country.ToString());
}
You are not using the ThreadPool- you are just starting up a Thread for each country:
Try this instead: