How to write multithread windows application that runs a program in given number of threads and show results of time taken from each thread. I tried to create it but I can see that my program shows incorrect result that means when I increase the number of threads , time taken by each thread increases as well (as shown by message box). following is my code:
private static void StartMultithread(long recordsToProcess, string connectionString, string stagingTableName, bool tableLockEnabled, bool transactionEnabled, int batchSize, bool userMultipleDatabases, bool userMultipleTables, bool userMultipleUsers, int bulkInsertTimeout)
{
Dictionary<string, Thread> threadPool = new Dictionary<string, Thread>();
for (int i = 0; i < threadCount; i++)
{
Thread thread = new Thread(new ParameterizedThreadStart(delegate(object tid)
{
int ii = (int)tid;
Core.BulkInsert bulkInsert1 = new Core.BulkInsert();
string result1 = bulkInsert1.Insert(recordsToProcess, connectionString, stagingTableName, tableLockEnabled, transactionEnabled, batchSize, bulkInsertTimeout);
MessageBox.Show (result1);
}));
thread.Name = i.ToString();
threadPool.Add(thread.Name, thread);
}
for (int i = 0; i < threadCount; i++)
{
Thread thread = threadPool[i.ToString()];
thread.IsBackground = true;
thread.Start(i);
}
for (int i = 0; i < threadCount; i++)
{
Thread thread = threadPool[i.ToString()];
thread.Join();
}
}
As a result when I give threadCount = 1 , time taken is 0.8 sec.
When it is 2 , time taken by both threads is approx 1.2 sec each.
when it is 3 , time taken by them individually is approx 1.7 sec.
bulkinsert1.Insert inserts the records to database , for each thread I am passing different tables (so that table lock should not be bottleneck for insertion)
I want that all thread takes minimum time , I suppose it should be 0.8 sec as taken when threadCount is given 1.
I am new to threading , please correct me if I am wrong anywhere
I’m not sure how you’re timing things as it’s not apparent from the code provided.
However, assuming
bulkInsert1.Insertis an IO intensive operation (meaning your threads mostly wait for an IO operation to complete), it is normal for completion times to increase as you increase the number of threads. You have more threads, but they are using some shared resources (e.g. MB bus, network card, a remote database, etc.). For example, if it takes 0.8s for the database to process an insert operation, it is normal for it to take longer to process two or more simultaneous connections doing the same thing– especially if those queries happen to block each other for some reason. Consequently, the completion times of your threads increase.