C# Mongo FirstOrDefaultAsync hangs

萝らか妹 提交于 2019-12-03 21:29:39

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/29656923/c-sharp-mongo-firstordefaultasync-hangs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!