2017-06-29 51 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