为什么在从分离的线程调用文本框时 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
}
}
与此同时 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
}
}
最佳答案
那不是因为调用。您的 UI 队列已满,可能是因为:
- 您经常调用
DoStuff()
- 您正在 UI 上做其他繁重的工作
更新:
根据已删除的评论,在文本框中放置 50K 的文本是问题的根源。考虑使用按需加载数据的智能文本框。应该已经准备好了。
关于c# - UI 线程在文本框调用期间卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15862008/