我可以访问特定的API,该API强制实施每秒约3次API调用的速度限制。我正在使用C#创建一个Windows服务,我想如果我只是在调用之间放置一个“Thread.Sleep(4000)
”,这会将每个调用延迟4秒。好吧,我有一个“for
”循环,循环10次,用于测试。在一秒左右的时间内,它将从API中提取的所有10条记录插入到我的数据库中。所以,Thread.Sleep(4000)
没有被遵守。我已经读过Thread.Sleep()
仅适用于当前线程。我对线程知之甚少,但我希望你们中的一个能告诉我我做错了什么,或者至少建议采用另一种方法来遵守API流量法。这是我的代码的相关部分:
using (SqlConnection connection = new SqlConnection("Data Source=localhost;Initial Catalog=*****;Integrated Security=true;"))
{
for (int i = 0; i < 10; i++)
{
movie = api.GetMovieInfo(i);
Thread.Sleep(4000);
if (string.IsNullOrEmpty(movie.title))
continue;
string queryString = string.Format("insert into movie values ('{0}')", movie.title);
SqlCommand command = new SqlCommand(queryString, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
答案 0 :(得分:1)
您可能会看到此行为,因为您对Thread.Sleep的调用发生在using语句中。虽然我仍然希望它至少花费4秒钟,但你说只用了一秒就插入了所有10条记录。您可以尝试从using语句中删除对Thread.Sleep的调用,以查看行为是否有所改善......
请参阅:C# exiting a using() block with a thread still running onthe scoped object
我认为Threading.Timer是一个更好的选择,但我也认为Thread.Sleep应该也可以运行:
for (int i = 0; i < 10; i++)
{
DoAPIWork();
Thread.Sleep(4000);
}
private void DoAPIWork()
{
using (SqlConnection connection = new SqlConnection("Data Source=localhost;Initial Catalog=*****;Integrated Security=true;"))
{
movie = api.GetMovieInfo(i);
if (string.IsNullOrEmpty(movie.title))
continue;
string queryString = string.Format("insert into movie values ('{0}')", movie.title);
SqlCommand command = new SqlCommand(queryString, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
答案 1 :(得分:0)
尝试在新线程
上执行它例如
for(int i = 0; i < 10; i++)
{
Thread executionThread = new Thread(() =>
{
//Call your api process here
DoWork();
});
executionThread.Start();
// This stops the current thread and wait for the executionThread
executionThread.Join();
}
and then let your DoWork() handle the sleep.
public void DoWork()
{
Thread.Sleep(4000);
// Do actual work here
}