【问题标题】:How to refactor async method to include await operators?如何重构异步方法以包含等待运算符?
【发布时间】:2015-12-04 18:57:17
【问题描述】:

我添加了一个异步任务,它使用MongoDB.Net driver 将列表分配给新的 Bson 文档。我收到有关该方法的警告,说我应该将 await 运算符添加到 API 调用中。

所以我尝试的是,在 API 调用中添加 await,但它给了我一个错误:

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

我知道我不能等待列表类型,但不确定该运算符的其他位置。我在想 Find 调用可以重构为一个任务,然后将客户分配给它的结果。

客户列表为参考类型。

有谁知道我应该如何将 await 运算符添加到 API 调用中?

这是我在方法中添加 await 运算符的地方:

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;
}

【问题讨论】:

    标签: c# asynchronous task mongodb-.net-driver


    【解决方案1】:

    这行代码:

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

    应该改成这样:

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

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

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

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

    【讨论】:

    • 好的我现在明白了,上面的编辑消除了错误。但是我注意到,当我尝试将返回的客户列表分配给客户类型的 Observable 集合(使用扩展方法)时,它不接受新的列表类型。
    • 我收到以下错误:错误 6 'System.Threading.Tasks.Task>' 不包含 'ToObservableCollection' 的定义并且找不到接受“System.Threading.Tasks.Task>”类型的第一个参数的扩展方法“ToObservableCollection”
    • 让你的方法返回一个Task&lt;ObservableCollection&lt;T&gt;&gt;
    • 好的,所以修改扩展方法以返回 Task> ?谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    相关资源
    最近更新 更多