Cha*_*lie 1 c# user-interface controls multithreading invoke
问候,我在从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
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
它在富文本框中打印以下内容:
thread 0started!
thread 1started!
thread 2started!
Checking thread
Checking thread
Checking thread
Checking thread
....
Run Code Online (Sandbox Code Playgroud)
它继续,"hello"消息不会被打印,并且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
Run Code Online (Sandbox Code Playgroud)
是什么原因,我该怎么办?
提前致谢.
该Invoke
方法同步运行您的委托 - 它等待UI线程实际运行它,然后再将控制权返回给调用者.
由于UI线程正在等待线程完成,因此会出现死锁.
相比之下,该BeginInvoke
方法异步运行您的委托 - 它立即返回,并且当UI线程空闲时,委托仅运行一段时间.