多个UI线程WPF的问题 [英] Problem with Multiple UI Threads WPF

查看:80
本文介绍了多个UI线程WPF的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个样式加载的wpf应用程序,我需要为窗口创建一个单独的UI线程。该窗口使用应用程序其余部分使用的样式。样式位于解决方案中嵌入的资源xaml中。该窗口的代码如下所示。

I have a style loaded wpf application and I need to create a separate UI thread for a window. The window uses styles that the rest of the application is using. The styles is in a resource xaml embedded in the solution. The window is created with code that looks like this.

Dim thread As New Thread(Sub()
                             Dim w As New TimelineSceneEd
                             w.Show()

                             System.Windows.Threading.Dispatcher.Run()
                         End Sub)
thread.SetApartmentState(ApartmentState.STA)
thread.Start()





当窗口调用InitializeCompenent()时,我得到以下异常



'设置属性'System.Windows.FrameworkElement.Style'抛出异常。'行号'27'和行位置'171'。



机智h内部异常:

{调用线程无法访问此对象,因为另一个线程拥有它。}



我的猜测是某个生成的类用于解析包含wpf程序样式的xaml文件,并且该类位于另一个主UI线程上。但是,如果我使用initlializecompenent运行一个dispatcher.invoke到主ui线程,我仍然会遇到问题。任何想法?





当然我无法查看任何源代码,因为这是框架代码。



When the window calls InitializeCompenent() I get the following exception

'Set property 'System.Windows.FrameworkElement.Style' threw an exception.' Line number '27' and line position '171'.

with the inner exception of:
{"The calling thread cannot access this object because a different thread owns it."}

My guess is that there is a generated class somewhere that is used to parse the xaml file containing the styles for the wpf program, and that this class is on the other main UI Thread. However if i run a dispatcher.invoke off to the main ui thread with initlializecompenent, I still get problems. Any ideas?


Of course I cannot look at any source code because this is framework code.

推荐答案

没有多个UI线程这样的东西。您只能拥有一个,即应用程序启动时创建的线程。这是唯一可以触及用户界面及其控件的线程。



在你的情况下,你使用第二个线程的Invoke告诉UI线程运行代码而不是相反。
There is no such thing as "multiple UI threads". You can only ever have one, the thread that's created when your application starts. That is the only thread that can touch the user interface and its controls.

In your case, you use Invoke from a second thread to tell the UI thread to run code, not the other way around.


为什么在UI上需要多个线程,尤其是在WPF上,它使用线程池来分派必须执行的操作。
Why would you need multiple threads on UI, especially on WPF, it uses a Thread pool to dispatch things that it have to do.


这篇关于多个UI线程WPF的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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