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();
MessageBox.Show("Done!");
}
}
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.
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");
}
}
await Task.Delay(5000); work normally
Why does dbcontext freeze WPF app each first click after reboot?
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.