【发布时间】:2018-04-19 21:50:41
【问题描述】:
我有一个要求,我必须在服务器端使用 Geocode API 验证大量地址(大约 5000 个)。因此我决定使用 parallel for 一次向 API 发送多个请求(以减少执行时间) 这是我的代码
//Address object
public class AddressModel
{
public int AddressID { get; set; }
public string AddressLineOne { get; set; }
public string AddressLineTwo { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
//Main code starts here
List<AddressModel> Addresses = GetAddressesFromFile(); //This will add around 5k addresses to the list
Parallel.For(0, Addresses.Count, i =>
{
System.Net.WebResponse response = ResolveAddressFromGoogle(Addresses[i]);
//Process google response
});
public System.Net.WebResponse ResolveAddressFromGoogle(AddressModel address)
{
System.Net.WebResponse response = null;
try
{
string urlGoogleApi = "https://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=false&key=mykey&components=postal_code:{1}";
urlGoogleApi = string.Format(urlGoogleApi, address.AddressLineOne, address.Zip.ZipCode);
System.Net.WebRequest req = System.Net.WebRequest.Create(urlGoogleApi );
req.Method = "GET";
response = req.GetResponse();
}
catch (Exception ex)
{
response = null;
}
return response;
}
但问题是每秒有超过 50 个请求被发送到 API,因此我收到了很多地址的查询限制响应。 有没有办法将请求限制为每秒 50 个?
我尝试了一种方法,如果响应包含 over_query_limit 字符串,我尝试将任务延迟 1 秒,就像这样
Parallel.For(0, Addresses.Count, i =>
{
label:
System.Net.WebResponse response = ResolveAddressFromGoogle(Addresses[i]);
//If response contain over_query_limit
Task.delay(1000);
goto label;
//else process google response normally
});
但它似乎不起作用。任何帮助将不胜感激
【问题讨论】:
-
循环执行一次发送 50 个怎么样?
标签: c# google-maps task-parallel-library