0

I want to run 10 threads on the same time and want to start a new one, if one is completed. So example: I create 10 Threads. If the 1. is finished, i want to start a new one, but i want to hold a maximum value of threads of 10.

How can i realize this?

I've tried it like this:

 for (int z = 0; z < 10; z++)
            {
                Thread t = new Thread(() => check(name)); T.Start();


                if (z == 9)
                {
                    z = 0;
                }

            }

The Problem is here, that the program doesnt wait for the Threads to finish. How can i realize it here?

Thanks!

Brandon Baba
  • 13
  • 1
  • 3

2 Answers2

1

First of all, it is better to avoid creating threads explicitly unless you are absolutely sure you know what you are doing (Thread resources are limited and thread object on its own quite heavyweight). In all the other cases prefer Task (or at least ThreadPool). For tasks you can use Task.WhenAll(array of tasks) method to wait for all the required tasks completion before resuming main execution flow.

But if for some reason you still need to use Thread class, you can use Thread.Join(thread) method to block executing thread and wait for all required threads to finish their jobs.:

foreach (var thread in jobThreads)
{
    thread.Join();
}
Anton Sorokin
  • 401
  • 1
  • 7
  • 10
  • hey, thanks for answering. but if i use Thread.Join(); my application just creates 1 Thread.. do you know my fail? :/ – Brandon Baba Jun 01 '17 at 22:00
0

search for Thread.Join:

"Blocks the calling thread until the thread represented by this instance terminates".

for (Thread t : threads) {
  t.join();
}

you can block multiple threads waiting for 1 thread.

Gabri T
  • 454
  • 2
  • 13