简体   繁体   English

我正在做async / await吗?

[英]Am I doing async/await correctly?

I'm trying to use async and await keywords for the first time and I have a doubt whether I'm doing this correctly. 我第一次尝试使用asyncawait关键字,我怀疑我是否正确地执行此操作。

In my WPF form's Loaded event I use a method: 在我的WPF表单的Loaded事件中,我使用了一个方法:

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: GetAllMessagesAsync()如下所示:

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 . 我不确定我是否得到任何异步 - 似乎整个窗口都在等待DataGrid ,但我的数据太小了,以至于我无法弄清楚它只是我的计算机滞后还是真的是DataGrid What's more, Visual Studio gives a warning: 更重要的是,Visual Studio发出警告:

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. 考虑使用'await'运算符等待非阻塞API调用,或'await Task.Run(...)'在后台线程上执行CPU绑定工作。

So I understand I would have to await something in GetAllMessagesAsync() ? 所以我理解我必须在GetAllMessagesAsync()等待一些东西? But what? 但是什么? And the new function would have to await some other async function as well? 新功能还需要等待其他一些async功能吗? I can't figure it out, I get into an infinite loop in my mind. 我无法弄清楚,我在脑海中陷入无限循环。

You can just return a Task directly: 您可以直接返回Task

public Task<List<Message>> GetAllMessagesAsync()
{
    return Task.Factory.StartNew(() => _context.Messages.ToList());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM