[英]How can I pause a loop (while, foreach, for, or otherwise) in C#?
[英]C# Console App HTTP API request in a foreach loop - how to pause loop at 100 loops then continue?
但是,由于我使用的是公共API,所以我的代码有效,一次最多只能请求100个请求。
目前,我正在使用foreach循环执行请求。 代码看起来像这样。
public static List<string> keyList = new List<string>();
public static string Uri1 = "api url address";
public static string URLreq;
public static List<string> reqs = new List<string>();
static void apiReq()
{
string filePath = "Path To File\\a.txt";
var fileLines = System.IO.File.ReadAllLines(filePath);
foreach(string s in fileLines)
{
keyList.Add(s);
}
for (int ab = 0; ab < keyList.Count; ab++)
{
URLreq = Uri1 + keyList[ab];
reqs.Add(URLreq);
}
foreach (string ra in reqs)
{
Uri uri = new Uri(ra);
// Create the web request
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(ra + " : " + reader.ReadToEnd());
}
}
Console.ReadLine();
}
您能否建议我如何使用此循环执行100个请求,然后暂停2秒钟,然后从循环101继续到200,然后暂停,从201继续到300,依此类推。
在您的方法中添加一个Counter,如下所示:
static void apiReq()
{
string filePath = "Path To File\\a.txt";
var fileLines = System.IO.File.ReadAllLines(filePath);
int requestCounter = 0; // Adding a counter
foreach(string s in fileLines)
{
keyList.Add(s);
}
for (int ab = 0; ab < keyList.Count; ab++)
{
URLreq = Uri1 + keyList[ab];
reqs.Add(URLreq);
}
foreach (string ra in reqs)
{
if (requestCounter % 100 == 0) // Every 100th step
{
Thread.Sleep(2000); // Wait for 2 seconds
}
Uri uri = new Uri(ra);
// Create the web request
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// ..
}
requestCounter++; // Count upwards
}
// ..
}
谢谢@Smartis!
我设法做到这一点:
foreach (string ra in reqs)
{
for (int o = 0; o < reqs.Count; o++)
{
requestCounter = reqs.IndexOf(ra);
}
Uri uri = new Uri(ra);
// Create the web request
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(ra + " : " + reader.ReadToEnd());
}
if (requestCounter % 100 == 0) // Every 100th step
{
System.Threading.Thread.Sleep(2000); // Wait for 2 seconds
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.