这是我的代码
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个 urlwebapi ( example1.com直到example5.com )
答案 0 :(得分: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),但流程基本相同
答案 1 :(得分:-2)
我建议使用httpClient。 这使得它成为了parc的一个步行..并且使用你正确处理处置。
(伪代码)
using (var client = new httpClient)
{
//your logic, and you can keep using client in this context.
}