c# - While loop without blocking console output -


i have been working on multithreaded console applications , wondering how this. use code control amount of threads created 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 while loop, console.writeline method in created blocked , not show until next free thread available.

is there way can prevent while loop blocking console.writeline call?

edit - reversed condition in while loop.

update

based on comments...

the line

while (threads >= maxthreads) ; 

is not way await change in thread state, because cause cpu spin in while statement. instead, use 1 of mechanisms intended thread synchronization, such semaphore.

here's an example of semaphoreslim used similar situation.

class theclub      // no door lists! {   static semaphoreslim _sem = new semaphoreslim (3);    // capacity of 3    static void main()   {     (int = 1; <= 5; i++) new thread (enter).start (i);   }    static void enter (object id)   {     console.writeline (id + " wants enter");     _sem.wait();     console.writeline (id + " in!");           // 3 threads     thread.sleep (1000 * (int) id);               // can here @     console.writeline (id + " leaving");       // time.     _sem.release();   } }