6

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?

user1166905
  • 2,612
  • 7
  • 43
  • 75
  • 2
    Solution: Offload your heavy data access code from the UI thread using [async / await](http://msdn.microsoft.com/en-us/library/hh191443.aspx). This way the UI thread will not be blocked and your window will load instantly. – Federico Berasategui Oct 09 '14 at 15:48
  • Good point. I haven't used async await too much, could you give me a simple example. – user1166905 Oct 09 '14 at 15:50

2 Answers2

12

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;
}
Community
  • 1
  • 1
Federico Berasategui
  • 43,562
  • 11
  • 100
  • 154
  • 1
    Since EF supports async natively it would probably be even better to simply call ToListAsync() instead of ToList(). Since ToListAsync() already returns a Task<>, it can be awaited directly instead of wrapping the call in Task.Run(). – Nick Muller Jul 24 '19 at 06:38
  • @NickMuller right, but this answer is from 2014, I don't recall EF having async versions of anything at the time. – Federico Berasategui Jul 25 '19 at 15:27
1

Unless you use a multi threading tool for ex: Background worker (recommended), putting a time consuming tasks in the windows code behind (same UI thread) will wait until everything gets executed to show the window. BackgroundWorker has a great advantage when ProgressBar is needed or using Loading... status

HichemSeeSharp
  • 3,240
  • 2
  • 22
  • 44