如何重构异步方法以包含等待运算符

本文关键字:包含 等待 运算符 异步方法 何重构 重构 | 更新日期: 2023-09-27 18:25:38

我添加了一个异步任务,它使用MongoDB.Net驱动程序为一个新的Bson文档分配一个列表。我得到一个关于方法的警告,说我应该在API调用中添加等待运算符。

因此,我所尝试的是向API调用添加await,但它给了我一个错误:

错误9无法等待'System.Collections.Generic.List'

我知道我不能等待列表类型,但不确定将运算符放在其他位置。我认为Find调用可以重构为Task,然后将结果分配给客户。

客户列表的类型仅供参考。

有人知道我应该如何将等待运算符添加到API调用中吗?

这就是我在方法上添加等待运算符的地方:

public async Task LoadDb()
{
    var customerCollection = StartConnection();
    try
    {
        customers = await customerCollection.Find(new BsonDocument()).ToListAsync().GetAwaiter().GetResult();
    }
    catch (MongoException ex)
    {
        //Log exception here:
        MessageBox.Show("A connection error occurred: " + ex.Message, "Connection Exception", MessageBoxButton.OK, MessageBoxImage.Warning);
    }
}

这是customerCollection来自的StartConnection()

public IMongoCollection<CustomerModel> StartConnection()
{
    var client = new MongoClient(connectionString);
    var database = client.GetDatabase("orders");
    //Get a handle on the customers collection:
    var collection = database.GetCollection<CustomerModel>("customers");
    return collection;
}

如何重构异步方法以包含等待运算符

这行代码:

customers = await customerCollection.Find(new BsonDocument()).ToListAsync().GetAwaiter().GetResult();

应该改为:

customers = await customerCollection.Find(new BsonDocument()).ToListAsync();

从您收到的错误消息中,您可以理解为什么第一个不正确。

无法等待'System.Collections.Generic.List'

调用GetResult会阻塞执行代码的线程,并等待调用GetResult的结果。GetResult将返回一个List<MongoDBApp.Models.CustomerModel>。显然,你不能等待一个通用的结果。而您可以等待ToListAsync的结果,这是一项任务。在您调用ToListAsync的情况下,您会得到一个Task<List<MongoDBApp.Models.CustomerModel>>。这是可以等待的。