为什么你可以跨线程的WinForms添加控件,而不是WPF? [英] Why can you cross thread adding controls in WinForms, but not WPF?

查看:128
本文介绍了为什么你可以跨线程的WinForms添加控件,而不是WPF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个虚拟的WinForms应用程序,我能够创建一个列表框在设计时,在运行时创建一个后台线程,然后添加控件从后台线程的列表框。但是,如果我没有在WPF一样,我得到一个错误。

In a dummy WinForms app, I'm able to create a ListBox at design time, create a background thread at runtime, and then add controls to the ListBox from the background thread. But if I did the same in WPF, I get an error.

为什么我能做到这一点的WinForms,而不是WPF?是我的WinForm的例子不一样的WPF吗?或者是有确实为什么它工作得很好,在WinForms和不是理由WPF?

Why am I am able to do this in WinForms, but not WPF? Is my WinForm example not the same as the WPF one? Or is there indeed a reason why it works just fine in WinForms and not 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; }));
    }
}

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

This is the error I receive. Pretty standard and expected:

推荐答案

的WinForms不严格有关检查跨线程问题。这可能是因为WinForms的实际上不具有如标签对照。相反,他们只是包装了那些在操作系统层面实现真正的控制。

WinForms isn't as strict about checking for cross-threading issues. This is probably because WinForms doesn't actually have controls such as labels. Rather, they are just wrappers around the real controls that are implemented at the OS level.

由于这是一个实现细节,也不能保证你的WinForms code将继续在今后的工作。 (这就是说,它不是在积极发展,它可能会继续工作。)

Since this is an implementation detail, there is no guarantee that your WinForms code will continue to work in the future. (That said, it isn't under active development so it will probably continue working.)

这篇关于为什么你可以跨线程的WinForms添加控件,而不是WPF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆