System.Activator.CreateInstance和线程

时间:2013-04-26 07:44:01

标签: c# multithreading activator

我正在调用一个外部应用程序,它将XML转换为PDF。

dynamic generator = null;
Assembly a = Assembly.LoadFrom(file);
Type type = a.GetType("Application.ConsoleStartup.Program");
generator = Activator.CreateInstance(type);

然后

generator.Run("testXML.xml");  

总的来说,事情是有效的。唯一的问题是,在某个时刻,新打开的应用程序需要STA线程。问题是我没有访问(或非常有限)这个新打开的应用程序。有没有办法绕过这个?请注意,我并不是线程专家。

错误如下:

error DCP999: [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.Controls.ContentControl..ctor()
   at System.Windows.Controls.ToolTip..ctor()
   at Application.Parser.Html.Model.Anchor.AfterInsert(IParseContext pc) in C:\work\Common\Main\Source\Parsers\HtmlParser\Model\Anchor.cs:line 31

3 个答案:

答案 0 :(得分:1)

为什么不使用:System.Diagnostics.Process

Process myProcess = new Process();
myProcess.StartInfo.FileName = file; 
myProcess.Start();

答案 1 :(得分:1)

您需要将以下内容添加到应用程序的main方法中:

[STAThread]
static void Main(string[] args)
{
    // ...

这可能取决于您尝试访问UI元素的新线程,通常每个应用程序只有一个线程可以执行此操作。

答案 2 :(得分:0)

没有新的应用程序,您正在将程序集加载到您自己的应用程序中。您可以使用Thread.SetApartmentStatehttp://msdn.microsoft.com/en-GB/library/system.threading.thread.setapartmentstate.aspx

更改主题的公寓模型