BanksySan
BanksySan

Reputation: 28520

Mongo `await FindAsync` doesn't compile.

When I try to use the await keyword with the FindAll(filter) method I end up with un-compilable code. e.g.:

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

is giving:

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'.

If I look at the source, the method is indeed returning a Task:

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

Any idea what's going on here?

Upvotes: 0

Views: 461

Answers (2)

matanso
matanso

Reputation: 1292

Your function should be async. i.e.

async Task<int> myFunc() Instead of int myFunc ()

Upvotes: 0

Gusman
Gusman

Reputation: 15161

Your function is not marked as async, not the mongo one but yours, the one which has the code.

In order to make async calls inside a function you must mark that function as async:

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

Else you will receive that compile error.

Upvotes: 1

Related Questions