2016-09-19 48 views
0

這裏是我的代碼如何同時運行多個Web客戶端?

try 
{ 
    for (int i = 0; i < RichTextbox2.Lines.Length; i++) 
    { 
     var length = urlwebapi.Lines.Length; 
     { 
      WebClient f = new WebClient(); 
      dynamic read = f.DownloadString(urlwebapi.Lines[(i % length)] + RichTextbox2.Lines[i]); 
      JObject o = JObject.Parse(read);    
     } 
    } 
} 
catch (WebException e) 
{ 
    MessageBox.Show(e.Message); 
} 

MessageBox.Show("done");     

樣品urlwebapi

http://example1.com/api.php?ex= 
http://example2.com/api.php?ex= 
http://example3.com/api.php?ex= 
http://example4.com/api.php?ex= 
http://example5.com/api.php?ex= 

的代碼只能在同一時間在urlwebapi運行一個。怎麼辦時,在同一時間

+1

看看[DownloadStringAsync](https://msdn.microsoft.com/de-de/library/system.net.webclient.downloadstringasync(v = vs.110).aspx)。這應該可以幫助你處理多個請求。 –

回答

-2

我建議使用HttpClient的代碼被執行,然後立即運行多達5 urlwebapiexample1.com直到example5.com)我得到。 這使得它在公園散步..並使用你正確處理處置。

(僞代碼)

using (var client = new httpClient) 
{ 
    //your logic, and you can keep using client in this context. 
} 
0

這裏是如何做到這一點的示例代碼:

public async Task<string[]> DownloadStringsAsync(string[] urls) 
    { 
     var tasks = new Task<string>[urls.Length]; 
     for(int i=0; i<tasks.Length; i++) 
     { 
      tasks[i] = DownloadStringAsync(urls[i]); 
     } 
     return await Task.WhenAll(tasks); 
    } 

    public async Task<string> DownloadStringAsync(string url) 
    { 
     //validate! 
     using(var client = new WebClient()) 
     { 
      //optionally process and return 
      return await client.DownloadStringTaskAsync(url) 
       .ConfigureAwait(false); 
     } 
    } 

我寧願使用的HttpClient(https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.118).aspx),但整體流程是基本相同

+0

或簡單地'返回等待Task.WhenAll(urls.Select(url => DownloadStringAsync(url)));' –