微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 对远程api的节流并行请求

我正在使用一个使用Google Maps Geocoding API的ASP.NET MVC应用程序.在一个批处理中,最多可能有1000个查询要提交给Geocoding API,因此我尝试使用并行处理方法来提高性能.负责为每个核心启动进程方法是:

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();
        }
    }

这基于我在Microsoft’s parallel computing web site上找到的模式文档.
问题是Google Api的限制为10 QPS(企业客户) – 我正在打击 – 然后我收到HTTP 403错误.这是一种我可以从并行处理中受益但是限制我正在做出的请求的方式吗?我尝试过使用Thread.Sleep,但它没有解决问题.任何帮助或建议将非常感谢.

解决方法

@H_404_17@ 听起来你错过了某种Max in Flight参数.您需要根据作业完成来限制提交,而不是仅在队列中有作业时进行循环.

似乎您的算法应该类似于以下内容

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐