并行http请求 [英] Parallel http requests

查看:489
本文介绍了并行http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有使API请求使用BackgroundWorker的last.fm网站的应用程序。起初我不知道有多少要求我会需要做。该响应包含的总页数,所以仅将第一次请求之后得到它。这是下面的代码。



<预类=郎-CS prettyprint-覆盖> 私人无效backgroundWorker_DoWork(对象发件人,DoWorkEventArgs E)
{
INT页面= 1;
INT总页数= 1;

,而(页面< =总页数)
{
如果(backgroundWorker.CancellationPending)
{
e.Cancel = TRUE;
的回报;
}

//这里是请求的一部分
串响应= RecentTracksRequest(用户名,从页);

如果(Response.Contains(LFM状态= \OK))
{
总页数= Convert.ToInt32(Regex.Match(响应,@总页数= (\d +))组[1]。价值);

MatchCollection匹配= Regex.Matches(响应。<跟踪方式>((| \\\
)*)? < /曲目>);
的foreach(在比赛赛米)
ParseTrack(m.Groups [1]。价值);
}
,否则
{
MessageBox.Show(错误发送请求,错误,
MessageBoxButtons.OK,MessageBoxIcon.Error);
的回报;
}

如果(页面> =总页数)
中断;

如果(总页数== 0)
中断;

如果(网页<总页数)
页++;
}

的问题是,在last.fm API实在是太慢了,它可能需要长达5秒得到回应。具有大数量的页面,装载将需要很长的时间。



我想使并行请求,比方说在时间3平行的请求。是否可以?如果是的话,我该怎么做呢?



非常感谢。


解决方案

您可以利用的< A HREF =http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx相对=nofollow> 的HttpClient ,假设你有网址的名单:

  VAR的客户=新的HttpClient(); 
变种任务= urls.Select(URL => client.GetAsync(URL).ContinueWith(T =>
{
VAR响应= t.Result;
响应。 EnsureSuccessStatusCode();

//做更多的事情
}));

如果您使用异步方法,你可以等待所有任务完成象下面这样:

  VAR的结果=等待Task.WhenAll(任务); 


I have an app that making API requests to the last.fm website using the backgroundWorker. Initially I don't know how many request I'm gonna need to make. The response contains the total number of pages, so I will only get it after the first request. Here is the code below.

    private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {            
        int page = 1;
        int totalpages = 1;

        while (page <= totalpages)
        {
            if (backgroundWorker.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            //Here is the request part
            string Response = RecentTracksRequest(username, from, page);

            if (Response.Contains("lfm status=\"ok"))
            {
                totalpages = Convert.ToInt32(Regex.Match(Response, @"totalPages=.(\d+)").Groups[1].Value);

                MatchCollection match = Regex.Matches(Response, "<track>((.|\n)*?)</track>");
                foreach (Match m in match)
                    ParseTrack(m.Groups[1].Value);
            }
            else
            {
                MessageBox.Show("Error sending the request.", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (page >= totalpages)
                break;

            if (totalpages == 0)
                break;

            if (page < totalpages)
                page++;
        }

The problem is that the last.fm API is really slow and it might take up to 5 seconds to get the responce. With a big number of pages, the loading will take a long time.

I want to make parallel requests, say 3 parallel requests at a time. Is it possible? If yes, how can I make it?

Thanks a lot.

解决方案

You can take advantage of HttpClient, assume you have list of url:

var client = new HttpClient();
var tasks = urls.Select(url => client.GetAsync(url).ContinueWith(t =>
            {
                var response = t.Result;
                response.EnsureSuccessStatusCode();

                //Do something more
            }));

If you use async method, you can await all tasks finish like below:

var results = await Task.WhenAll(tasks);

这篇关于并行http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆