gpt4 book ai didi

c# - .Net 最大并发计时器线程数

转载 作者:太空狗 更新时间:2023-10-29 20:13:57 25 4
gpt4 key购买 nike

我正在尝试加载间隔进程队列。换句话说,我有一个队列,我希望队列中的每个项目都在一个单独的时间间隔内运行。

我的问题是我似乎无法同时运行超过 25 个线程。我在默认最大线程数为 32768 的 64 位机器上使用 .Net 4.5。

如何让我的应用程序运行尽可能多的并发线程,因为我的机器可以处理?

这是一个示例应用程序,它复制了我的生产代码中的实际问题:

class Program
{
static void Main(string[] args)
{
System.Threading.ThreadPool.SetMaxThreads(200, 200);
test t = new test();

t.LoadUrls("http://www.google.com");

while (1 == 1)
{
System.Threading.Thread.Sleep(1000);//refresh every 5 seconds
Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().Threads.Count);
}
}


public class test
{

public void LoadUrls(string url)
{
for (int i = 0; i < 100; i++)
{
System.Threading.Timer t = new System.Threading.Timer(new System.Threading.TimerCallback(RunInterval), url, 0, 1000);
Console.WriteLine("Loaded {0} feeds.", i);
}
}
private static void RunInterval(object state)
{
string url = state as string;
string data = "";

using (System.Net.WebClient cl = new System.Net.WebClient())
{
Console.WriteLine("getting data for " + url);
data = cl.DownloadString(url);
}

//do something with the data

}
}
}

这段代码理论上应该在 2 秒左右后运行 198 个线程。

顺便说一下,这在我的原型(prototype)应用程序中运行得非常好;它是用节点编写的。但是,现在我无法让它在 c# 中正常工作...

回答:问题实际上出在垃圾回收上,根本不是线程池问题;该池不仅能够假脱机我扔给它的所有线程。诀窍是使用 System.Threading.Timer 的单参数构造函数;这将使计时器将自身用作信号量,从而避免 gc。

class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
test t = new test();
t.url = "http://www.google.com?" + i;
System.Threading.Timer ti = new System.Threading.Timer(new System.Threading.TimerCallback(t.RunInterval));
ti.Change(0, 1000);
}

while (1 == 1)
System.Threading.Thread.Sleep(int.MaxValue);
}


public class test
{
public string url { get; set; }
public void RunInterval(object state)
{
Console.WriteLine("getting data for " + this.url);
string data = "";

using (System.Net.WebClient cl = new System.Net.WebClient())
{
data = cl.DownloadString(this.url);
}
}
}
}

我不确定为什么您会希望 gc 收集计时器,但嘿,我知道什么。

最佳答案

How do I make my app run as many concurrent threads as my machine can handle?

这是错误的做法。每个线程的成本都很高,创建几百个线程就会严重降低系统性能。

您的代码使用线程池。池有一个算法来限制线程的数量。当您增加 Sleep() 时间时,您可能会看到更多线程。

更直接的方法是设置 ThreadPool.MinThreads。但期望性能更低,而不是更多。

关于c# - .Net 最大并发计时器线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14265430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com