shirbr510 shirbr510 - 1 year ago 66
C# Question

MongoCollection returns data sync but not async

I've been trying to convert a

logic to
and realized that my
async await
pattern doesn't work.

I've changed this code:

var filter = Builders<SmartAgentProperty>.Filter.Where(smartAgent => smartAgent.UserMail==userMail);
var results = await SmartAgentsCollection.FindAsync(filter);
return results.ToList();

to this:

var filter = Builders<SmartAgentProperty>.Filter.Where(smartAgent => smartAgent.UserMail == userMail);
var results = SmartAgentsCollection.Find(smartAgent => smartAgent.UserMail == userMail).ToEnumerable();
return Task.FromResult(results);

version works perfectly.

version is hanging and doesn't throw any exceptions.

as it sounds, this is an extremely wierd bug.

I thought I might be doing things wrong but seems like the same pattern works in other places in my code so I'm reaching out for help.

Answer Source

So based on Craig's Comment, issue solved!

a. I was using it wrong (Task.FromResult instead of actual async implementation)

b. I was missing the configureAwait(false)

c. should have used Find(filter).ToListAsync() instead of FindAsync(filter).ToEnumerable()

here's the code after fixing it:

return await _smartAgentsCollection
      .Find(smartAgent => smartAgent.UserMail == userMail)