4

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})
Chadit
  • 965
  • 2
  • 12
  • 27
  • 2
    You probably need to add a ConfigureAwait to the end of the call so that you don't deadlock your main thread. return await GetCollection.Find(query).FirstOrDefaultAsync().ConfigureAwait(false); – Craig Wilson Apr 15 '15 at 19:35
  • 1
    However, in this case, there really isn't any reason you need to use the async and await keywords... just return GetCollection.Find(query).FirstOrDefaultAsync(); – Craig Wilson Apr 15 '15 at 19:36
  • removing the async and await worked... not sure why, I assumed because it was FirstOrDefaultAsync it needed an await flag – Chadit Apr 15 '15 at 23:44
  • 1
    How exactly are you calling `GetFirst()`? Are you using something like `GetFirst(query).Result`? – svick Apr 15 '15 at 23:55
  • I call the GetFirst with the await flag, so something like this await repo.GetFirst(filterQuery); – Chadit Apr 16 '15 at 11:34

1 Answers1

8

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();
    }
    
Craig Wilson
  • 12,174
  • 3
  • 41
  • 45