0

这是我的代码

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上同时运行一个。执行代码时如何获得然后立即同时运行最多 5 个urlwebapiexample1.com 直到 example5.com

4

2 回答 2

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 ) 但流程基本相同

于 2016-09-19T11:33:44.967 回答
-3

我建议使用 httpClient。这使得它在公园里散步。并且使用你可以正确处理处置。

(伪代码)

using (var client = new httpClient)
{
  //your logic, and you can keep using client in this context.
}
于 2016-09-19T11:31:20.777 回答