2016-09-19 46 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)));' –