2016-09-19 8 views
0

は、ここに私のコードのコードは唯一同時にurlwebapiで1を実行することができます複数の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= 

です。コードが実行されたとき、どのように私はその後すぐに、私はHttpClientを使用して提案を

+1

[DownloadStringAsync](https://msdn.microsoft.com/de-de/library/system.net.webclient.downloadstringasync(v = vs.110).aspx)を参照してください。複数のリクエストを処理するのに役立ちます。 –

答えて

-2

に同時に(example5.comまでexample1.com)5 urlwebapiまで実行されますか。 それはそれをparcで散歩させます..そして、あなたが適切に処分することを使用して。

は(擬似コード)

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

私は(https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.118).aspx)のHttpClientを使用することを好むだろうが、流れは基本的に同じです

+0

または単に 'return await Task.WhenAll(urls.Select(url => DownloadStringAsync(url)));' –

関連する問題