3

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

Francesco Re
  • 836
  • 6
  • 22
  • Pomelo (and MySqlConnector) claim to support async properly. I recommend that you upgrade to the latest versions and then, if the issue persists, [raise an issue with the Pomelo team](https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql/issues). – Stephen Cleary Jan 27 '19 at 02:29

2 Answers2

0

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.

haimb
  • 381
  • 3
  • 4
  • Hi,thanks for the reply. No, I'm doing only one query at the time. With the solution of Hubert Jarema it works. Maybe async does not mean on a different thread... – Francesco Re Jan 18 '19 at 15:11
  • It doesn't. It depends on the implementation of the method, but I want to believe that EF is implemented properly... – haimb Jan 19 '19 at 15:54
-2

You are incorrectly calling your async method from a button click event. It should be like this:

await Task.Run(()=> api.GetMyUserAsync());

Look at the answer here: How to run and interact with an async Task from a WPF gui

bobek
  • 8,003
  • 8
  • 39
  • 75