【发布时间】:2014-11-12 19:12:54
【问题描述】:
Parallel.ForEach 继续运行,我的程序没有结束。我无法追踪它在第一次迭代后的去向。我的猜测是它会陷入僵局并继续进行上下文切换。
private void ReadInputFile()
{
var collection = new ConcurrentBag<PropertyRecord>();
var lines = System.IO.File.ReadLines(InputFileName);
int i = 0;
int RecordsCount = lines.Count();
Parallel.ForEach(lines, line =>
{
if (string.IsNullOrWhiteSpace(line))
{
return;
}
var tokens = line.Split(',');
var postalCode = tokens[0];
var country = tokens.Length > 1 ? tokens[1] : "england";
SetLabelNotifyTwoText(
string.Format(
"Reading PostCode {0} out of {1}"
i,
lines.Length));
var tempRecord = GetAllAddesses(postalCode, country);
if (tempRecord != null)
{
foreach (PropertyRecord r in tempRecord)
{
collection.Add(r);
}
}
});
}
private List<PropertyRecord> GetAllAddesses(
string postalCode,
string country = "england")
{
SetLabelNotifyText("");
progressBar1.Value = 0;
progressBar1.Update();
var records = new List<PropertyRecord>();
using (WebClient w = new WebClient())
{
var url = CreateUrl(postalCode, country);
var document = w.DownloadString(url);
var pagesCount = GetPagesCount(document);
if (pagesCount == null)
{
return null;
}
for (int i = 0; i < pagesCount; i++)
{
SetLabelNotifyText(
string.Format(
"Reading Page {0} out of {1}",
i,
pagesCount - 1));
url = CreateUrl(postalcode,country, i);
document = w.DownloadString(url);
var collection = Regex.Matches(
document,
"<div class=\"soldDetails\">(.|\\n|\\r)*?class=" +
"\"soldAddress\".*?>(?<address>.*?)(</a>|</div>)" +
"(.|\\n|\\r)*?class=\\\"noBed\\\">(?<noBed>.*?)" +
"</td>|</tbody>");
foreach (var match in collection)
{
var r = new PropertyRecord();
var bedroomCount = match.Groups["noBed"].Value;
if(!string.IsNullOrEmpty(bedroomCount))
{
r.BedroomCount = bedroomCount;
}
else
{
r.BedroomCount = "-1";
}
r.address = match.Groups["address"].Value;
var line = string.Format(
"\"{0}\",{1}",
r.address
r.BedroomCount);
OutputLines.Add(line);
Records.Add(r);
}
}
}
return Records;
}
在没有Parallel.ForEach 的情况下运行良好,但需要使用Parallel.ForEach。
我已经调试过了,第一次从GetAllAdresses-method 返回后,Step Next 按钮停止,它只是在后台继续调试。它不会出现在我放置的任何书签上。
【问题讨论】:
-
从这里调试会更加困难。
-
我已经调试过了,第一次从 GetAllAddresses(..) 返回,我不知道在哪里
-
请使用调试器。还有
SetLabelNotifyText和SetLabelNotifyTwoText有什么作用?那叫control.Invoke吗?那个主线程是哪个线程调用的? -
是的,他们在那里阻止非法线程访问问题以更新 GUI
-
@Charlie 很高兴为您提供帮助,但这绝对不是我们这里的远程调试会话!请自己做你的功课并调查正在运行的任务/线程/堆栈!不太可能有答案指出困扰您的那条线,因为这个问题不符合SSCCE。
标签: c# .net task-parallel-library parallel.foreach