C# 阻止对远程api的并行请求
我正在开发一个ASP.NETMVC应用程序,它使用谷歌地图地理编码API。在一个批处理中,可能有多达1000个查询提交到地理编码API,因此我尝试使用并行处理方法来提高性能。负责启动每个核心流程的方法是:C# 阻止对远程api的并行请求,c#,asp.net,parallel-processing,C#,Asp.net,Parallel Processing,我正在开发一个ASP.NETMVC应用程序,它使用谷歌地图地理编码API。在一个批处理中,可能有多达1000个查询提交到地理编码API,因此我尝试使用并行处理方法来提高性能。负责启动每个核心流程的方法是: public void GeoCode(Queue<Job> qJobs, bool bolKeepTrying, bool bolSpellCheck, Action<Job, bool, bool> aWorker) { // Get the
public void GeoCode(Queue<Job> qJobs, bool bolKeepTrying, bool bolSpellCheck, Action<Job, bool, bool> aWorker)
{
// Get the number of processors, initialize the number of remaining
// threads, and set the starting point for the iteration.
int intCoreCount = Environment.ProcessorCount;
int intRemainingWorkItems = intCoreCount;
using(ManualResetEvent mreController = new ManualResetEvent(false))
{
// Create each of the work items.
for(int i = 0; i < intCoreCount; i++)
{
ThreadPool.QueueUserWorkItem(delegate
{
Job jCurrent = null;
while(qJobs.Count > 0)
{
lock(qJobs)
{
if(qJobs.Count > 0)
{
jCurrent = qJobs.Dequeue();
}
else
{
if(jCurrent != null)
{
jCurrent = null;
}
}
}
aWorker(jCurrent, bolKeepTrying, bolSpellCheck);
}
if(Interlocked.Decrement(ref intRemainingWorkItems) == 0)
{
mreController.Set();
}
});
}
// Wait for all threads to complete.
mreController.WaitOne();
}
}
public void GeoCode(队列qJobs、bool bolkeptrying、bool bolSpellCheck、动作aWorker)
{
//获取处理器数量,初始化剩余处理器数量
//线程,并设置迭代的起点。
int intcorecont=Environment.ProcessorCount;
int intRemainingWorkItems=intCoreCount;
使用(ManualResetEvent mreController=新的ManualResetEvent(错误))
{
//创建每个工作项。
对于(int i=0;i0)
{
锁(qJobs)
{
如果(qJobs.Count>0)
{
jCurrent=qJobs.Dequeue();
}
其他的
{
if(jCurrent!=null)
{
jCurrent=null;
}
}
}
a工作人员(jCurrent、bolKeepTrying、bolSpellCheck);
}
if(联锁减量(参考INTREMAININGWORKIMS)==0)
{
mreController.Set();
}
});
}
//等待所有线程完成。
mreController.WaitOne();
}
}
这是基于我在文档中找到的模式。
问题是,GoogleAPI限制了10个QPS(企业客户)——我正在达到这个限制——然后我得到了HTTP403错误。这是一种我可以从并行处理中获益,但限制我的请求的方式吗?我试过使用线程。睡眠,但它不能解决问题。如果您有任何帮助或建议,我们将不胜感激。听起来您好像遗漏了某种最大飞行参数。当队列中有作业时,您需要根据作业完成情况限制提交,而不仅仅是循环 看起来您的算法应该如下所示:
submit N jobs (where N is your max in flight)
Wait for a job to complete, and if queue is not empty, submit next job.
谢谢你的回复-这让我对这个问题有了不同的思考。