加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 21:08:45 所属栏目:百科 来源:网络整理
导读:我正在使用一个使用Google Maps Geocoding API的ASP.NET MVC应用程序.在一个批处理中,最多可能有1000个查询要提交给Geocoding API,因此我尝试使用并行处理方法来提高性能.负责为每个核心启动进程的方法是: public void GeoCode(QueueJob qJobs,bool bolKeep
我正在使用一个使用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,但它没有解决问题.任何帮助或建议将非常感谢.

解决方法

听起来你错过了某种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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读