C# 如何在新的AppDomain中运行WPF应用程序?可执行程序集失败

C# 如何在新的AppDomain中运行WPF应用程序?可执行程序集失败,c#,wpf,applicationdomain,C#,Wpf,Applicationdomain,我正在尝试使用应用程序域从控制台应用程序启动WPF应用程序, 但当我这样做时,我会收到意想不到的错误 独立运行WPF应用程序,可以正常工作 这段代码也适用: var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; var path = string.Format("{0}AddressbookDesktop.exe", baseDirectory); var processInfo = new ProcessStartInfo(pat

我正在尝试使用应用程序域从控制台应用程序启动WPF应用程序, 但当我这样做时,我会收到意想不到的错误

独立运行WPF应用程序,可以正常工作

这段代码也适用:

var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var path = string.Format("{0}AddressbookDesktop.exe", baseDirectory);
var processInfo = new ProcessStartInfo(path, "");
Process.Start(processInfo);    
但此代码失败,错误如下。错误出现在构造函数中,该构造函数为空:

var addressbookDomain = AppDomain.CreateDomain("addressbookDomain");
addressbookDomain.ExecuteAssembly("AddressbookDesktop.exe");
堆栈跟踪:

System.Windows.Markup.XamlParseException: Cannot create instance of 
'AddressbookMainWindow' defined in assembly 'AddressbookDesktop, Version=1.0.0.0, 
Culture=neutral, PublicKeyToken=null'. Exception has been thrown
by the target of an invocation. Error in markup file 'AddressbookMainWindow.xaml' Line     1 Position 9.
---> 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.Controls.ContentControl..ctor()
at System.Windows.Window..ctor()
at XX.YY.AddressbookDesktop.AddressbookMainWindow..ctor() in      C:\.....\AddressBookDesktop\AddressbookMainWindow.xaml.cs:line 15
--- End of inner exception stack trace ---
我想我做错了什么,但不明白是什么。
感谢您的帮助。

问题是WPF必须从STA线程运行(上面的一个内部异常说明了这一点)。通过将添加到我的
Main()
方法,我实现了这一点:

using System;

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        Console.WriteLine("Starting WpfApplication1.exe...");

        var domain = AppDomain.CreateDomain("WpfApplication1Domain");
        try
        {
            domain.ExecuteAssembly("WpfApplication1.exe");
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        finally
        {
            AppDomain.Unload(domain);
        }

        Console.WriteLine("WpfApplication1.exe exited, exiting now.");
    }
}