I have been working on some multithreaded console applications recently and was wondering how to do this. I use this code to control the amount 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 is blocked and does not show up until the next free thread is available.
Is there any way I can prevent this while loop from blocking the Console.WriteLine
call?
EDIT - Reversed condition in while loop.
UPDATE
Based on your comments...
The line
while (threads >= maxThreads) ;
is not a good way to await a change in thread state, because it will cause the CPU to spin in the while statement. Instead, use one of the mechanisms intended for thread synchronization, such as a Semaphore.
Here's an example of a 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();
}
}
Using the while loop and thread.abort (or thread.suspned) etc are CPU intensive and is not the right way for thread synchronization. Explore Manual and AutoResetEvents. They are very effective when it comes to thread synchronization and does not spike your CPU.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With