我正在设置.Text
的{{1}}值,禁用它,然后调用textbox
来执行冗长的文件系统操作。在BackgroundWorker
操作的大约一半之前,文本框不会使用新文本值进行更新。
如何强制texbox尽快显示新文本值?相关代码如下:
BackgroundWorker
更新:我解决了这个问题。这是与此无关的代码 - 我覆盖了void BeginCacheCandidates()
{
textBox1.Text = "Indexing..."; // <-- this does not update until about 20 to 30 seconds later
textBox1.Enabled = false;
backgroundWorker1.RunWorkerAsync();
}
void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
//prime the cache
CacheCandidates(candidatesCacheFileName);
}
void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
textBox1.Text = "";
textBox1.Enabled = true;
textBox1.Focus();
}
并且它已进入循环......
答案 0 :(得分:1)
除非我遗漏了一些细节,否则ReportProgress不会给你你想要的东西吗?
void BeginCacheCandidates()
{
textBox1.Text = "Indexing...";
textBox1.Enabled = false;
backgroundWorker1.ReportProgress += new ProgressChangedEventHandler(handleProgress)
backgroundWorker1.RunWorkerAsync();
}
void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
//prime the cache
backgroundWorker1.ReportProgress(<some int>, <text to update>);
CacheCandidates(candidatesCacheFileName);
}
void handleProgress(object sender, ProgressChangedEventArgs e)
{
...
textBox1.Text = e.UserState as String;
...
}
答案 1 :(得分:1)
尝试在文本框上调用更改,而不是直接调用它。
textBox1.BeginInvoke(new MethodInvoker(() => { textBox1.Text = string.Empty; }));
这将导致在Form的主题上发生更改。
答案 2 :(得分:0)
使用Form.Update()
方法强制进行UI更新。
void BeginCacheCandidates()
{
textBox1.Text = "Indexing..."; // <-- this does not update until about 20 to 30 seconds later
textBox1.Enabled = false;
this.Update(); // Force update UI
backgroundWorker1.RunWorkerAsync();
}