2012-10-31 141 views
1

我有一個應用程序使用backgroundWorker向last.fm網站發出API請求。起初我不知道我需要做多少請求。該響應包含頁面的總數,所以我只會在第一次請求後才能得到它。這是下面的代碼。並行http請求

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++; 
     } 

的問題是last.fm API實在是太慢了,它可能需要長達5秒得到迴應。如果頁面數量很多,加載將需要很長時間。

我想進行並行請求,一次說3個並行請求。可能嗎?如果是的話,我該怎麼做?

非常感謝。

+0

順便說一句,如果您向sa我主持(您的情況是last.fm).NET將限制併發http請求的數量。請參閱此處接受的答案:http://stackoverflow.com/questions/1361771/max-number-of-concurrent-httpwebrequests – Dmitry

回答

7

你可以採取的HttpClient優勢,假設你有URL列表:

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

       //Do something more 
      })); 

如果使用異步方法,你可以等待所有任務完成如下:

var results = await Task.WhenAll(tasks); 
+0

「Parallel.ForEach」的另一種方法 –

1

你可以做異步的Web請求以及使用BeginGetResponse

 HttpWebRequest webRequest; 
     webRequest.BeginGetResponse(new AsyncCallback(callbackfunc), null); 


     void callbackfunc(IAsyncResult response) 
     { 
     webRequest.EndGetResponse(response); 
     }