C# 如何限制特定间隔内的线程数?
我的问题是,我有一个方法,应该在特定的时间间隔调用,并在该时间间隔调用特定数量的线程,然后在下次调用后保持空闲 为了更清楚,我在下面提供了一个示例代码:C# 如何限制特定间隔内的线程数?,c#,multithreading,threadpool,C#,Multithreading,Threadpool,我的问题是,我有一个方法,应该在特定的时间间隔调用,并在该时间间隔调用特定数量的线程,然后在下次调用后保持空闲 为了更清楚,我在下面提供了一个示例代码: namespace ThreadTest { public partial class Form1 : Form { public Form1() { Initialize Components(); } } public void ExtractDatafromW
namespace ThreadTest
{
public partial class Form1 : Form
{
public Form1()
{
Initialize Components();
}
}
public void ExtractDatafromWebPage()
{
//Code for extracting data from web page using HTTPWebRequest and HTTPWebResponse class
}
private void btn1_Click(object sender, EventArgs e)
{
// On clicking the button the ExtractDatafromWebPage() method should be called with 5 threads at every 10 seconds.
}
}
现在我的要求是每10秒调用一次该方法,每次只有5个线程与该方法关联,并且在接下来的10秒之前保持空闲。此过程将无限继续。如果我正确理解您的问题,您可以执行如下所示的类似操作(因为我不确定您所说的“只有5个线程与此方法关联”是什么意思) 如果您的意思是只有五个线程应该进入该方法,那么只需要有一个计数为“5”的信号量 传入需要生成的线程数、时间段等
private void btn1_Click(object sender, EventArgs e)
{
// On clicking the button the ExtractDatafromWebPage() method should be called with 5 threads at every 10 seconds.
Timer t = new System.Threading.Timer(
() =>
{
for (int i = 1; i <= 5; i++)
{
//you can use thread pool thread
new Thread(() => this.ExtractDatafromWebPage()).Start();
}
}, null, 0, 10 * 1000);
}
private void btn1\u单击(对象发送者,事件参数e)
{
//单击该按钮时,应每隔10秒使用5个线程调用ExtractDatafromWebPage()方法。
计时器t=新的System.Threading.Timer(
() =>
{
对于(int i=1;i this.ExtractDatafromWebPage()).Start();
}
},空,0,10*1000);
}
请不要在问题标题中包含关于所用语言的信息,除非没有它就没有意义。标记用于此目的。您使用的是哪个.NET版本?