I’m trying to use async and await keywords for the first time and I have a doubt whether I’m doing this correctly.
In my WPF form’s Loaded event I use a method:
private void MessagesWindowLoaded(object sender, RoutedEventArgs e)
{
DataGridMessagesLoadAsync();
}
Which looks like this:
private async void DataGridMessagesLoadAsync()
{
_messages = await _messageService.GetAllMessagesAsync();
dataGridMessages.ItemsSource = _messages;
if (_messages.Count() == 0) return;
dataGridMessages.Columns[6].Visibility = System.Windows.Visibility.Collapsed;
dataGridMessages.Columns[8].Visibility = System.Windows.Visibility.Collapsed;
dataGridMessages.Columns[10].Visibility = System.Windows.Visibility.Collapsed;
dataGridMessages.Columns[11].Visibility = System.Windows.Visibility.Collapsed;
dataGridMessages.Columns[12].Visibility = System.Windows.Visibility.Collapsed;
}
The GetAllMessagesAsync() looks like this:
public async Task<List<Message>> GetAllMessagesAsync()
{
return (from m in _context.Messages select m).ToList();
}
I’m not sure whether I get any asynchrony – it seems like the whole window is waiting for the DataGrid, but my data is so small that I can’t figure out whether it’s just my computer lag or really the DataGrid. What’s more, Visual Studio gives a warning:
This async method lacks ‘await’ operators and will run
synchronously. Consider using the ‘await’ operator to await
non-blocking API calls, or ‘await Task.Run(…)’ to do CPU-bound work
on a background
thread.
So I understand I would have to await something in GetAllMessagesAsync()? But what? And the new function would have to await some other async function as well? I can’t figure it out, I get into an infinite loop in my mind.
You can just return a
Taskdirectly: