2017-06-29 56 views
0

我的应用程序工作正常,但现在我想有自定义开机,这样我就可以捕捉任何错误,从一开始就加我的日志等如何在使用自定义启动时“恢复”SynchronizationContext?

所以我使用的方法如本答案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为空。我需要它:-)

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

回答

1

请勿创建您自己的Main方法。重写OnStartup方法在App.xaml.cs文件:

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属性。

+1

太好了,我有我想要的所有功能,非常感谢! – astrowalker