使用自定义启动时如何"restore" SynchronizationContext?

How to "restore" SynchronizationContext when using custom startup?

我的应用程序运行良好,但现在我想要自定义启动,这样我就可以捕获任何错误,从一开始就添加我的日志记录等。

所以我使用了这个答案中所示的方法What code controls the startup of a WPF application?

[STAThread]
public static void Main(string[] args) {
    //include custom startup code here

    var app = new MyApplication();//Application or a subclass thereof
    var win = new MyWindow();//Window or a subclass thereof
    app.Run(win); //do WPF init and start windows message pump.
}

它工作正常,但有一个例外 -- SynchronizationContext.Current 为空。我需要它:-)

那么如何正确的自定义启动并拥有同步上下文呢?

不要创建自己的 Main 方法。覆盖 App.xaml.cs 文件中的 OnStartup 方法:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        var win = new MyWindow();
        win.Show();
    }
}

然后你会像往常一样得到一个SynchronizationContext

不要忘记从 App.xaml 文件的 <Application> 根元素中删除 StartupUri 属性。