我如何将以下内容转换为Parallel.ForEach?
public async void getThreadContents(String[] threads)
{
HttpClient client = new HttpClient();
List<String> usernames = new List<String>();
int i = 0;
foreach (String url in threads)
{
i++;
progressLabel.Text = "Scanning thread " + i.ToString() + "/" + threads.Count<String>();
HttpResponseMessage response = await client.GetAsync(url);
String content = await response.Content.ReadAsStringAsync();
String user;
Predicate<String> userPredicate;
foreach (Match match in regex.Matches(content))
{
user = match.Groups[1].ToString();
userPredicate = (String x) => x == user;
if (usernames.Find(userPredicate) != user)
{
usernames.Add(match.Groups[1].ToString());
}
}
progressBar1.PerformStep();
}
}
我原本的编码假设异步和并行处理是一样的,但我刚刚意识到它们是不同的。我查看了所有我能找到的相关问题,但好像都找不到一个适合我的示例。大部分示例中使用难以理解的变量名,只用单个字母的变量名不能清楚地说明其包含的内容。
我的线程数组(包含论坛帖子的URL)通常有300到2000个条目,因为要进行多个HTTP请求,所以采用并行处理似乎可以加速执行。
在使用Parallel.ForEach之前,我是否需要将所有异步操作都删除?我该如何做?我能否在不阻塞主线程的情况下完成此操作?
顺便说一下,我正在使用.NET 4.5。