Winform和WPF 两种框架在子线程需要对主界面(UI)控件进行操作的时候,都是不能直接访问或修改主界面控件的。但两者对主界面的控件进行操作的方法也略有不同,详细代码如下:
Winform:
private void UpdateUI(string text)
{
if (textBox1.InvokeRequired)
{
// 使用BeginInvoke方法异步调用主线程上的方法
textBox1.BeginInvoke(new Action<string>(UpdateUI), text);
}
else
{
// 在主线程上更新UI控件
textBox1.Text = text;
}
}
private void StartThread()
{
Thread thread = new Thread(() =>
{
// 子线程中调用UpdateUI方法来更新UI控件
UpdateUI("Hello, world!");
});
thread.Start();
}
WPF:
public void UpdateUI(string txt)
{
this.Dispatcher.Invoke(new Action(() =>
{
Run r = new Run(txt);
Paragraph para = new Paragraph();
para.Inlines.Add(r);
richtxtBox.Document.Blocks.Add(para);
}));
}
private void StartThread()
{
Thread thread = new Thread(() =>
{
// 子线程中调用UpdateUI方法来更新UI控件
UpdateUI("Hello, world!");
});
thread.Start();
}
需要注意的是两个方法不能混用,winform用第一个,wpf用第二个不要混淆。