【发布时间】:2010-01-11 16:59:22
【问题描述】:
我有一个应用程序,其中两个线程异步写入单个文本框。它可以工作,只是第二个线程写入文本框会覆盖第一个线程刚刚写入的行。对问题的任何想法或见解将不胜感激。我正在使用 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);
}
}
【问题讨论】:
-
您到底想让我们做什么?这是 2 个线程写入同一事物时的预期行为...您要改为附加文本吗??
-
SetText函数追加文本。 -
看起来您的代码将按照编写的方式运行。也许您在发布此内容时编辑了导致错误的内容?
标签: c# delegates multithreading backgroundworker