Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Mongo FirstOrDefaultAsync hangs

using the 2.0 driver the following code will sometimes hang and never return.

public async Task<T> GetFirst(FilterDefinition<T> query)
{
    return await GetCollection.Find(query).FirstOrDefaultAsync();
}

if I debut and put a break point on the return line, everything returns normally. In the shell the query being run is something like this:

db.Customers.find({"Name" : /test$/i})
like image 408
Chadit Avatar asked Feb 11 '23 10:02

Chadit


1 Answers

There are 2 solutions:

  1. Add a ConfigureAwait(false) at the end:

    return await GetCollection.Find(query).FirstOrDefaultAsync().ConfigureAwait(false);
    
  2. Just return the Task<T>, since the result of FirstOrDefaultAsync() is the same type as the result you want to return.

    public Task<T> GetFirst(FilterDefinition<T> query)
    {
        return GetCollection.Find(query).FirstOrDefaultAsync();
    }
    
like image 116
Craig Wilson Avatar answered Feb 13 '23 02:02

Craig Wilson