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)
那不是因为调用。您的 UI 队列已满,可能是因为:
DoStuff()你经常打电话更新:
根据已删除的评论,将 50K 文本放入文本框中是问题的根源。考虑使用按需加载数据的智能文本框。那里应该已经准备好了一个。
| 归档时间: |
|
| 查看次数: |
1367 次 |
| 最近记录: |