【发布时间】:2017-04-23 00:04:38
【问题描述】:
我编写了一个扩展,用于跨线程更新带有 HTML 文本的 RichTextBox(使用 HtmlAgilityPack 解析)。现在我也需要纯文本,从 HTML 标记中剥离,这正是 innerText 返回。
但是如何从委托中返回呢?
public static string AppendHTMLText(this RichTextBoxEx box, string html)
{
// cross thread allowed
if (box.InvokeRequired)
{
box.Invoke((MethodInvoker)delegate()
{
return AppendHTMLText(box, html); // ???
});
}
else
{
HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
//document.OptionFixNestedTags = false;
//document.OptionCheckSyntax = false;
//document.OptionWriteEmptyNodes = true;
document.LoadHtml(html);
HtmlAgilityPack.HtmlNode doc = document.DocumentNode.SelectSingleNode("/");
HtmlAgilityPack.HtmlNodeCollection nodes = doc.ChildNodes;
parseHTML(doc.ChildNodes, box);
return doc.InnerText;
}
}
}
谢谢!
【问题讨论】:
-
Invoke() 返回值,将其转换为(字符串)。您必须使用正确的委托类型,
Func<string>使用 lambda 表达式完成工作: return (string)box.Invoke(new Func(() => { return AppendHTMLText(box, html); }) );不是那么漂亮且容易死锁,请支持异步/等待或在 UI 线程上继续的小型后台任务。 -
@Hans,谢谢,我已经完全按照你的解释弄清楚了。感谢您的努力。
标签: c# richtextbox html-agility-pack