0

I wrote a extension for cross thread update a RichTextBox with a HTML text (parsed with HtmlAgilityPack). Now I need plain text too, stripped from HTML tags and this is exact innerText return.

But how to return from delegate too?

 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;
        }

    }
}

Thank you!

yo3hcv
  • 1,531
  • 2
  • 17
  • 27
  • 1
    Invoke() returns the value, cast it to (string). You have to use the proper delegate type, `Func` gets the job done with a lambda expression: return (string)box.Invoke(new Func(() => { return AppendHTMLText(box, html); })); Not that pretty and liable to deadlock, do favor async/await or small background tasks that continuewith on the UI thread. – Hans Passant Apr 22 '17 at 13:05
  • @Hans, thank you, I already figured out exactly as what you explained. Thanks for effort. – yo3hcv Apr 23 '17 at 14:48

1 Answers1

1

I would do it the following way:

public static void AppendHTMLText(this RichTextBoxEx box, string html)
{
    // use HtmlAgilityPack here
    // ...
    string text = doc.InnerText;

    if (box.InvokeRequired)
    {
        box.Invoke((MethodInvoker)delegate()
        {
            box.AppendText(text);
        });
    }
    else
    {
        box.AppendText(text);
    }
}
Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49