App_Startup() VS OnStartup() when launching a WPF application

Viewed 1475

I am starting a new WPF project and I need lighting on the launch of the application.

I watched 2 different WPF projects to see how to begin.

  • The first one starts with the void App_Startup(object sender, StartupEventArgs e) method in the App.xaml.cs file, called directly from the App.xaml file (Startup="App_Startup").
  • The other one starts with the protected override void OnStartup(StartupEventArgs e) method in the App.xaml.cs file.

In addition of that, when I started my WPF project, the default code template starts in a third way with StartupUri="MainWindow.xaml" in the App.xaml file.

What are the differences between this three manners?

2 Answers

Startup="App_Startup" is just event handler for your application, which is started in App.xaml. It has event StartUp which you can subscribe to. If you want to have some "pre-loading" logic, this is perfect place.

If you want to have just your window shown, it is enough to specify URI (in StartUpUri) of that window, so application knows which file to load and what window to show :)

OnStartup raises event of application start (in base.OnStratUp), from the documentation:

OnStartup raises the Startup event.

A type that derives from Application may override OnStartup. The overridden method must call OnStartup in the base class if the Startup event needs to be raised.

There also can be put some pre-loading logic.

There is none recommended way, it is up to you and what you need.

Startup is an event that is raised by the OnStartup method of the Application base class as you can see in the reference source. This is how it's implemented:

protected virtual void OnStartup(StartupEventArgs e)
{
    VerifyAccess();

    StartupEventHandler handler = (StartupEventHandler)Events[EVENT_STARTUP];
    if (handler != null)
    {
        handler(this, e);
    }
}

So if you override OnStartup in your App class and call base.OnStartup(e), the event will be raised and any attached event handler will be invoked. Whether you implement your logic in the event handler or directly in the overridden OnStartup is a matter of personal or application specific preference. There are no recommendations on why one should be better than the other.

When it comes to the StartupUri, it only makes sense to set this when you simply want to display a default window immediately on startup and you don't have any custom initialization logic.

In enterprise apps, it's common to have some kind of bootstrapper that sets up the application and its dependencies and create and show the main window programmatically rather than using the StartupUri property.

Related