我有一个应用程序,其中两个线程异步写入单个文本框。它可以工作,只是写入文本框的第二个线程会覆盖第一个线程刚刚写入的行。对这个问题的任何想法或见解将不胜感激。我正在使用 Microsoft Visual C# 2008 Express Edition。谢谢。
delegate void SetTextCallback(string text);
private void SetText(string text)
{
this.textBox1.Text += text;
this.textBox1.Select(textBox1.Text.Length, 0);
this.textBox1.ScrollToCaret();
}
private void backgroundWorkerRx_DoWork(object sender, DoWorkEventArgs e)
{
string sText = "";
// Does some receive work and builds sText
if (textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { sText });
}
else
{
SetText(sText);
}
}
最佳答案
编辑:这可能无法解决问题,但您可能想要处理 ProgressChanged
BackgroundWorkers 的事件并在那里设置文本。
例如:
void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) {
SetText((string)e.UserState);
} //Make this method handle the RunWorkerCompleted for both workers
//In DoWork:
worker.ReportProgress(0, sText);
ProgressChanged 在 UI 线程上触发,因此您不需要调用 Invoke
.
顺便说一句,您可能应该重命名 SetText
至AppendText
让代码更清晰。
另外,您可以使用内置委托(delegate) Action<String>
而不是自己制作SetTextCallback
委托(delegate)类型。
编辑:另外,您可能应该移动 InvokeRequired
检查SetText
.
例如:
private void AppendText(string text) {
if(textBox1.InvokeRequired) {
textBox1.Invoke(new Action<string>(AppendText), text);
return;
}
this.textBox1.AppendText(text);
this.textBox1.SelectionStart = textBox1.TextLength;
this.textBox1.ScrollToCaret();
}
关于c# - C# 中对文本框的异步写入被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2043373/