Search code examples
c#wpfloadingstartuplaunch

Execute multiple functions on program load - C#, WPF


I'm trying to get my WPF application to run several functions/methods on program launch. I'd like to accomplish this with no user input (ie, user must first click a button, etc).

Where do I place the code that calls these functions, on program launch?


Solution

  • You could call them in your program's Main function, or in the constructor of the first window you create.

    You might consider running them in another thread like this, if the data isn't needed immediately.

    await Task.Run(() => 
    {
        InitFunction1("arguments");
        InitFunction2("arguments");
    });
    

    Or using other task/async tools for loading them in parallel, or in an otherwise non-blocking fashion.

    Using the WPF Tutorial as a reference point. You might put it in the main window constructor, or otherwise override and create your own version of the InitializeComponent method.

    public MainWindow()
    {
        YourCustomInitializationFunction();
        InitializeComponent();
    }
    

    In order to run the initialization method asynchronously, move it to an async Loaded event handler:

    public MainWindow()
    {
        InitializeComponent();
        Loaded += async (s, e) => await YourCustomInitializationFunction();
    }