Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Window - When to load data so form appears instantly

Tags:

c#

wpf

Using Entity Framework in a WPF application and wondering if I'm going about loading the data all wrong. I put the following in the code behind:

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        var invoices = db.Invoices.AsNoTracking().ToList();
        listbox1.ItemsSource = invoices;
    }

Loads ok, no problem there, however the window is not displayed until the data has loaded which is tedious. Is wWindow_loaded the best method/time to load it?

like image 900
user1166905 Avatar asked Oct 09 '14 15:10

user1166905


1 Answers

as mentioned in my comment, all you need is to liberate the UI thread from heavy work, so it can freely do UI related work.

All you need is to use these "magical" words in C# async / await:

private async void Window_Loaded(object sender, RoutedEventArgs e)
{
    var invoices = await Task.Run(() => db.Invoices.AsNoTracking().ToList());
    listbox1.ItemsSource = invoices;
}
like image 108
Federico Berasategui Avatar answered Nov 10 '22 01:11

Federico Berasategui