【问题标题】:Mongo `await FindAsync` doesn't compile.Mongo `await FindAsync` 无法编译。
【发布时间】:2016-02-07 00:55:27
【问题描述】:

当我尝试将 await 关键字与 FindAll(filter) 方法一起使用时,我最终得到了不可编译的代码。例如:

using (var cursor = await collection.FindAsync(filter))
{
    while (await cursor.MoveNextAsync())
    {
        var batch = cursor.Current;
        foreach (var document in batch)
        {
            // process document
            count++;
        }
    }
}

正在给予:

The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

如果我查看源代码,该方法确实返回了Task

public static Task<IAsyncCursor<TDocument>> FindAsync<TDocument>(...)

知道这里发生了什么吗?

【问题讨论】:

    标签: c# mongodb visual-studio-2010 async-await


    【解决方案1】:

    你的函数没有被标记为异步,不是mongo,而是你的,有代码的那个。

    为了在函数内部进行异步调用,您必须将该函数标记为异步:

    public async void YourFunction()
    { 
        //Here you can use await
    }
    

    否则您将收到该编译错误。

    【讨论】:

    • 就是这样,谢谢。这是一种测试方法,我没有想到!
    • async void?绝对不行。让它async Task.
    【解决方案2】:

    你的函数应该是异步的。 即

    async Task&lt;int&gt; myFunc() 代替 int myFunc ()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-27
      • 2017-09-08
      • 1970-01-01
      • 2017-09-11
      • 2019-12-15
      • 2014-05-06
      • 1970-01-01
      相关资源
      最近更新 更多