First call of dbcontext freezes an app after each app reboot

.net-core c# entity-framework entity-framework-core wpf


We have a test WPF application (.NET Core 3.0) with only one button in center of the screen. The button have a click event and a method for its processing:

private async void CreateUsers(object sender, RoutedEventArgs e)
        using (var context = new AsyncDbContext())
            await context.Users.AddRangeAsync(new List<User>
                     new User{Name="1"},
                     new User{Name="2"},
                     new User{Name="3"},
                     new User{Name="4"},
                     new User{Name="5"},
                     new User{Name="6"},
                     new User{Name="7"},
                     new User{Name="8"},
            await context.SaveChangesAsync();

This method is async, so we expecting, that UI will not freeze after button click. But, if we start the app and click button, the app freezes on 1-2 seconds. If we will make another clicks it works as expected without freezes.

After it we reboot our app and the situation come again.

  1. Database was created
  2. .Net framework work exactly the same
  3. DbContext:

    public class AsyncDbContext:DbContext
        public DbSet<User> Users { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            optionsBuilder.UseSqlServer("Server=ServerName;Database=AsyncDb3; Trusted_connection=true");
  4. await Task.Delay(5000); work normally

  5. Wrapping these actions in await Task.Run(...) work normally

Why does dbcontext freeze WPF app each first click after reboot?

4/10/2020 8:04:52 AM

Popular Answer

It is not related to async or Tasks. The behavior you are seeing is arising from the fact that EF must generate and cache the model represented by a context upon first query. This happens before the async point in SaveChanges() since EF must figure out what queries to generate, hence the pause.

What you can do to help matters along is issue a "do nothing" query at application startup, perhaps in another thread, which causes this caching to happen upfront rather than as a result of some user action.

4/10/2020 12:59:56 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow