Although a loop without locking the console output

I recently worked on several multithreaded console applications and wondered how to do this. I use this code to control the number of threads created by the application:

foreach(string s in File.ReadAllLines("file.txt")){ while (threads >= maxThreads) ; Thread t = new Thread(() => { threads++; //thread code - make network request using 's' Console.WriteLine("TEST"); threads--; Thread.CurrentThread.Abort(); }); t.start(); } 

However, due to the while loop, the Console.WriteLine method in the created one is locked and does not appear until the next free stream.

Is there any way to prevent this loop from blocking the call to Console.WriteLine ?

EDIT - A reverse condition in a while loop.

+5
source share
2 answers

UPDATE

Based on your comments ...

Line

 while (threads >= maxThreads) ; 

This is not a good way to wait for a thread to change state, because it will cause the processor to spin in the while statement. Instead, use one of the mechanisms designed to synchronize threads, such as Semaphore .

Here's an example of SemaphoreSlim used for a very similar situation.

 class TheClub // No door lists! { static SemaphoreSlim _sem = new SemaphoreSlim (3); // Capacity of 3 static void Main() { for (int i = 1; i <= 5; i++) new Thread (Enter).Start (i); } static void Enter (object id) { Console.WriteLine (id + " wants to enter"); _sem.Wait(); Console.WriteLine (id + " is in!"); // Only three threads Thread.Sleep (1000 * (int) id); // can be here at Console.WriteLine (id + " is leaving"); // a time. _sem.Release(); } } 
+6
source

Using while loop and thread.abort (or thread.suspned), etc. works intensively on the CPU and is not suitable for thread synchronization. Explore Manual and AutoResetEvents. They are very effective when it comes to thread synchronization and do not accumulate your processor.

+4
source

All Articles