UI线程在文本框调用期间冻结

dov*_*ska 5 c# user-interface multithreading freeze backgroundworker

为什么UI在从分离的线程调用的文本框中冻结

    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
        }
    }
Run Code Online (Sandbox Code Playgroud)

同时backgroundworker工作得很好 - UI不会冻结

    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
        }
    }
Run Code Online (Sandbox Code Playgroud)

Xaq*_*ron 1

那不是因为调用。您的 UI 队列已满,可能是因为:

  1. DoStuff()你经常打电话
  2. 你还在 UI 上做其他繁重的工作

更新:

根据已删除的评论,将 50K 文本放入文本框中是问题的根源。考虑使用按需加载数据的智能文本框。那里应该已经准备好了一个。