Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UI thread freezes during textbox invoking

Why UI freezes during textbox invoking from separated thread

    private void button1_Click(object sender, EventArgs e)
    {
        Thread t1 = new Thread(DoStuff);
        t1.Start();
    }

    void DoStuff()
    {
        using (var wc = new System.Net.WebClient())
        {
            string page_src = wc.DownloadString("http://bing.com");
            textBox1.Invoke((MethodInvoker)delegate() { textBox1.Text = page_src; }); // freezes while textbox text is changing
        }
    }

Meanwhile backgroundworker works perfectly - UI doesn't freeze

    private void button1_Click(object sender, EventArgs e)
    {
        BackgroundWorker bw1 = new BackgroundWorker();
        bw1.DoWork += (a, b) => { DoStuff(); };
        bw1.RunWorkerAsync();
    }

    void DoStuff()
    {
        using (var wc = new System.Net.WebClient())
        {
            string res = wc.DownloadString("http://bing.com");
            textBox1.Invoke((MethodInvoker)delegate() { textBox1.Text = res; }); // works great
        }
    }
like image 300
dovydas juraska Avatar asked Nov 13 '22 07:11

dovydas juraska


1 Answers

That's not because of invoke. Your UI queue is full, and it may be because:

  1. You are calling DoStuff() frequently
  2. You are doing other heavy jobs on UI

Update:

According to deleted comment putting 50K of text in text-box was the source of problem. Consider using a smart text box which loads data on demand. There should be one ready out there.

like image 57
Xaqron Avatar answered Nov 15 '22 08:11

Xaqron