![](/img/trans.png)
[英]Windows Workflow Foundation NullReferenceException
[英]Windows Workflow Foundation with Windows Presentation Foundation
我試圖在Workflow Com服務中創建一個WPF窗口但是我收到以下錯誤:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: The calling thread must be STA, because many UI components require this.
at System.Windows.Input.InputManager..ctor()
at System.Windows.Input.InputManager.GetCurrentInputManagerImpl()
at System.Windows.Input.InputManager.get_Current()
at System.Windows.Input.KeyboardNavigation..ctor()
at System.Windows.FrameworkElement.FrameworkServices..ctor()
at System.Windows.FrameworkElement.EnsureFrameworkServices()
at System.Windows.FrameworkElement..ctor()
at System.Windows.Controls.Control..ctor()
at System.Windows.Window..ctor()
at PACIExpress.SelectLanguage..ctor()
有人可以幫我嗎?
Exception准確地說明了問題:
System.InvalidOperationException:調用線程必須是STA,因為許多UI組件都需要這個。
首先,如果'Workflow Com Service'類似於WCF或Web服務,那么它不是可以擁有用戶界面的桌面應用程序。
無論哪種方式,您的應用必須是STA。
MTA和STA之間的區別:
有關WPF和STA的信息: http : //msdn.microsoft.com/en-gb/magazine/cc163328.aspx
如果您有入口點方法,則需要使用STAThread屬性,請參閱此處以獲取更多信息:
http://blogs.msdn.com/b/jfoscoding/archive/2005/04/07/406341.aspx http://msdn.microsoft.com/en-us/library/system.stathreadattribute.aspx
希望有所幫助!
Kieren的答案解釋了問題的本質,即Workflow Foundation線程是MTA線程,而WPF需要STA線程。 Kieren的答案並未解釋如何解決問題。
每當我需要從MTA線程訪問WPF內容時,我都會創建一個用於訪問內容的STA線程。 我已經使用了兩個解決方案,這兩個解決方案都運行良好:
匯集的STA線程
當WPF對象不需要存在於當前方法調用之外時,我使用我編寫的STAThreadPool類。 STAThreadPool實現System.Threading.ThreadPool的基本功能,但創建其線程STA而不是MTA。 它還有一個RunOnSTAThread方法,該方法對用戶工作項進行排隊,然后等待該項完成。
專用STA線程
此解決方案具有更多開銷,但是對於多個方法調用,任何時候都可能存在WPF對象。 同樣有一個“RunOnSTAThread”方法,在這種情況下通過以下方式實現:
每個STA線程運行一個執行此操作的循環:
這個解決方案實際上比編寫良好的STAThreadPool更少的代碼,但如果有很多線程可能效率較低。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.