gpt4 book ai didi

c# - 为什么在 WinForms 中可以跨线程添加控件,而在 WPF 中不能?

转载 作者:行者123 更新时间:2023-11-30 12:59:05 26 4
gpt4 key购买 nike

在虚拟 WinForms 应用程序中,我能够在设计时创建一个 ListBox,在运行时创建一个后台线程,然后从后台线程向 ListBox 添加控件。但是,如果我在 WPF 中执行相同的操作,则会出现错误。

为什么我可以在 WinForms 中执行此操作,但不能在 WPF 中执行此操作?我的 WinForm 示例与 WPF 示例不同吗?或者它确实在 WinForms 而不是 WPF 中工作正常的原因是什么?

WinForms:

private List<Label> _labels;

public Form1()
{
InitializeComponent();

Thread test = new Thread(DoStuff);
test.SetApartmentState(ApartmentState.STA);
test.Start();
}

private void DoStuff()
{
_labels = new List<Label>();

_labels.Add(new Label() { Text = "Label1" });
_labels.Add(new Label() { Text = "Label2" });
_labels.Add(new Label() { Text = "Label3" });

if (listBox1.InvokeRequired)
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.DataSource = _labels; });
}
else
{
listBox1.DataSource = _labels;
}
}

WPF:

public partial class MainWindow : Window
{
private ObservableCollection<Label> _labels;
public MainWindow()
{
InitializeComponent();

Thread test = new Thread(DoStuff);
test.SetApartmentState(ApartmentState.STA);
test.Start();
}

private void DoStuff()
{
_labels = new ObservableCollection<Label>();
_labels.Add(new Label() { Content = "Label1" });
_labels.Add(new Label() { Content = "Label2" });
_labels.Add(new Label() { Content = "Label3" });

this.Dispatcher.BeginInvoke((Action)(() =>{ icMain.ItemsSource = _labels; }));
}
}

这是我收到的错误。非常标准和预期:

enter image description here

最佳答案

WinForms 在检查跨线程问题方面并不严格。这可能是因为 WinForms 实际上并没有标签之类的控件。相反,它们只是在操作系统级别实现的实际控件的包装器。

由于这是一个实现细节,因此无法保证您的 WinForms 代码将来会继续工作。 (也就是说,它没有在积极开发中,所以它可能会继续工作。)

关于c# - 为什么在 WinForms 中可以跨线程添加控件,而在 WPF 中不能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27237724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com