Loading color scheme

How to start several threads and wait them to finish in C#

If you need some work to be done in parallel, you will need to use threads. Usually, this work includes downloading some data from the server, processing multiple documents at once, launching several instances of the class at the same time, etc. 

But how do you start several threads at once? Here is the code example:

const int nThreadCount = 8;

Thread[] workerThreads = new Thread[nThreadCount];

/* Start Threads */
for (int k = 0; k < nThreadCount; k++)
{
	workerThreads[k] = new Thread(ThreadFunction);
	workerThreads[k].Start(/*optional thread data */);
}

/* Wait for all Threads to finish */
for (int k = 0; k < nThreadCount; k++)
{
	workerThreads[k].Join();

}

private void ThreadFunction(object parameterObject)
{
	/* do some work in a thread */
	
}

nThreadCount is the constant that specifies how many threads are we going to launch at once.

in a first loop, we create thread objects and specify their starting functions. then, we start the threads. 

The second loop waits for all threads to finish. 

Of course, when using threads, you will need to take care of data consistency to avoid race conditions.

 

Get all interesting articles to your inbox
Please wait