我最近一直在研究一些多线程控制台应用程序,并想知道如何做到这一点.我使用此代码来控制应用程序创建的线程数量:
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();
}
Run Code Online (Sandbox Code Playgroud)
但是,由于while循环,Console.WriteLine创建的方法被阻止,并且在下一个空闲线程可用之前不会显示.
有什么方法可以防止这种阻止Console.WriteLine呼叫的循环吗?
编辑 - while循环中的反转条件.
UPDATE
根据你的评论......
这条线
while (threads >= maxThreads) ;
Run Code Online (Sandbox Code Playgroud)
不是等待线程状态更改的好方法,因为它会导致CPU在while语句中旋转.而是使用一种用于线程同步的机制,例如信号量.
这是一个用于非常类似情况的SemaphoreSlim 的示例.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
712 次 |
| 最近记录: |