Async method blocks UI in WPF

Viewed 1049

I'm making a WPF app that simply get some data from the database and display it. I've used EntityFrameworkCore with the Pomelo connector for mysql. The connection to the database works perfectly, and also data is retrieved correctly. The problem is that even if I use an async method with await, the UI blocks everytime. This is the code of the Click listener

private async void BT_Click(object sender, RoutedEventArgs e)
    {
        var userTask = api.GetMyUserAsync();
        Console.WriteLine("started task");
        var users = await userTask;
        Console.WriteLine(users.Name);
    }

And this is the code of the query in Api.cs:

public async Task<User> GetMyUserAsync()
    { 
        return await context.User
            .Where(u => u.Username == username && u.Password == password)
            .FirstOrDefaultAsync();
    }

I can't figure out why this is happening. Also other answers suggest this code, but for me it doesn't work.

Francesco

2 Answers

This shouldn't happen. A method which is declared to be asynchronous (with the Async suffix) should not block when used with await and your code should work fine.

Are you running another query in the background? EF core doesn't support running multiple requests simultaneously (see the first warning). If you are, try to make all of your queries run one by one.

Related