【发布时间】:2011-08-26 03:27:09
【问题描述】:
您好,我在从 C# 中的工作线程调用 RichTextBox 时遇到问题。我正在使用 InvokeRequired/Invoke 方法。请看我的代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ThreadSafe(MethodInvoker method)
{
if (InvokeRequired)
Invoke(method);
else
method();
}
private void WorkerThread(object data)
{
string msg = "\nhello, i am thread " + data.ToString();
ThreadSafe(delegate
{
richTextBox1.AppendText(msg);
});
}
private void button1_Click(object sender, EventArgs e)
{
Thread[] workers = new Thread[3];
for (int i = 0; i < 3; i++)
{
workers[i] = new Thread(WorkerThread);
workers[i].Start(i);
string msg = "\nthread " + i.ToString() + "started!";
richTextBox1.AppendText(msg);
}
int j = 3;
while (j > 0)
{
for (int i = 0; i < 3; i++)
{
Thread.Sleep(250);
richTextBox1.AppendText("\nChecking thread");
if (workers[i].Join(250))
{
string msg = "\nWorker thread " + i.ToString() + " finished.";
richTextBox1.AppendText(msg);
workers[i] = null;
j--; // decrement the thread watch count
}
}
}
}
}
它在富文本框中打印以下内容:
thread 0started!
thread 1started!
thread 2started!
Checking thread
Checking thread
Checking thread
Checking thread
....
它继续,“你好”消息没有被打印,并且 UI 被冻结。 然后我把Invoke()改成了BeginInvoke(),我知道不应该这样做,结果是这样的:
thread 0started!
thread 1started!
thread 2started!
Checking thread
Worker thread 0 finished.
Checking thread
Worker thread 1 finished.
Checking thread
Worker thread 2 finished.
hello, i am thread 0
hello, i am thread 1
hello, i am thread 2
这是什么原因,我该怎么办?
提前致谢。
【问题讨论】:
标签: c# multithreading user-interface controls invoke