有没有办法在 WPF 中跨两个 STA 线程使用对象? [英] Is there any way to use an object across two STA threads in WPF?

查看:44
本文介绍了有没有办法在 WPF 中跨两个 STA 线程使用对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,在任何人开始之前,让我说清楚...

Okay, before anyone starts up, let me be clear...

我使用的是自定义控件,在本例中是 Telerik 的 RadPane.当您反序列化这些窗格时,它们通过回调方法进入,因此,全部由一个线程拥有/反序列化,并且它们不能被克隆或深度复制等,因此我正在尝试处理一些巨大的限制.这很糟糕,因为我想向每个窗格添加内容,但希望它们都在自己的 UI 线程范围内工作.例如,我想将一个列表添加到一个窗格中,并让它更新数百万条记录等,但如果我更新一个窗格,UI 线程将锁定所有窗格.

I'm using a custom control, in this case Telerik's RadPane. When you deserialize these panes they come in through a callback method, and thus, are ALL owned/deserialized by one thread, and they cannot be cloned or deep copied, etc. so there are some huge limitations I am trying to work with. This is bad because, I want to add content to each pane but want them all to work within the confines of their own UI thread. For example, I want to add a list to a pane and have it update with millions of records, etc. but if I update one pane, the UI thread will lock up for all panes.

我需要在不同的线程中创建此对象的内容,但问题是,当我尝试设置内容时,明显的问题是该对象不属于拥有我的窗格的同一线程:

I need to create the contents of this object in a different thread, but the problem is, when I try to set the content, the obvious issue is that the object is not owned by the same thread that owns my pane:

myRadPane.Content = myGrid;

myGrid 由与 myRadPane 不同的线程拥有,因此它不想设置内容.在 WPF 中有没有办法解决这个问题,或者有什么方法可以让一个对象跨 UI 线程共享"?

myGrid is owned by a different thread than myRadPane, so it doesn't want to set the content. Is there any way around this problem in WPF or a way to allow one object to be "shared" across UI threads?

请注意,我完全了解调度程序的工作方式,每当主 UI 线程需要为一个窗格更新时,我的应用程序都会使用它们.但是,在这种情况下,即使尽可能少地使用调度程序,UI 线程也会在高负载下陷入困境.

Please note, I am fully aware of how dispatchers work, and my application makes use of them whenever the main UI thread needs updating for one pane. However, in this case, even while using dispatchers as minimally as possible, the UI thread bogs down under heavy load.

推荐答案

您可以复制 WPF 控件.

You CAN copy WPF controls.

在你的创建者线程中调用:

Call this in your creater Thread:

    public string CopyWPFControl<T>(T source)
    {
        string childXaml = XamlWriter.Save(source);
        var stringReader = new StringReader(childXaml);
        return stringReader.ToString();
    }

将您的结果传输到您的 Dispatcher/STA 线程并调用:

Transfer your result to your Dispatcher / STA thread and call:

    public T RecreateWPFControl<T>(string source)
    {
        var xmlReader = XmlReader.Create(source);
        var clonedChild = (T)XamlReader.Load(xmlReader);
        return clonedChild;
    }

因此,在不同的线程中创建您的对象,然后复制控件及其所有绑定等并使用输出进行显示.

So create your object in a Diferent Thread, then copy the Control and all its Bindings ect and use the output to display.

导入后只会复制 XAML 描述.

imported this will only copy the XAML description.

这篇关于有没有办法在 WPF 中跨两个 STA 线程使用对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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