Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - show loading while not finished?

Tags:

c#

.net

loading

In my C# application I start the program up by reading a HTML page and parsing some links out of it and putting them into a richTextBox (for now). But the problem is, that because it has to read the links it takes some time, so when I start the program it takes about 5 seconds before the form is shown. What I would like to do is show the form immediately, and show a loading cursor or a disabled richTextBox. How would I go about doing that? Here is a sample of what happens:

public Intro()
        {
            InitializeComponent();
            WebClient wc = new WebClient();
            string source = wc.DownloadString("http://example.com");

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(source);
            var nodes = doc.DocumentNode.SelectNodes("//a[starts-with(@class, 'url')]");
            foreach (HtmlNode node in nodes)
            {
                HtmlAttribute att = node.Attributes["href"];
                richTextBox1.Text = richTextBox1.Text + att.Value + "\n";

            }

        }
like image 725
Gregor Menih Avatar asked Nov 21 '25 11:11

Gregor Menih


1 Answers

OK, a little (I hope it's all correct) sample how you could do it with Task Parallel Library (What? I like it...)

public Intro()
{
    InitializeComponent();

    richTextBox1.IsEnabled = false;
    Task.Factory.StartNew( () =>
    {
       WebClient wc = new WebClient();
       string source = wc.DownloadString("http://example.com");

       HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
       doc.LoadHtml(source);
       var nodes = doc.DocumentNode.SelectNodes("//a[starts-with(@class, 'url')]");
       return nodes;
    }).ContinueWith( result =>
    {
      richTextBox1.IsEnabled = true;

      if (result.Exception != null) throw result.Exception;

      foreach (var node in result.Result)
      {
           HtmlAttribute att = node.Attributes["href"];
           richTextBox1.Text = richTextBox1.Text + att.Value + "\n";
      }

    }, TaskScheduler.FromCurrentSynchronizationContext());
}
like image 155
Patryk Ćwiek Avatar answered Nov 24 '25 01:11

Patryk Ćwiek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!