I am writing a very, very simple query which just gets a document from a collection according to its unique Id. After some frusteration (I am new to mongo and the async / await programming model), I figured this out:
IMongoCollection<TModel> collection = // ...
FindOptions<TModel> options = new FindOptions<TModel> { Limit = 1 };
IAsyncCursor<TModel> task = await collection.FindAsync(x => x.Id.Equals(id), options);
List<TModel> list = await task.ToListAsync();
TModel result = list.FirstOrDefault();
return result;
It works, great! But I keep seeing references to a "Find" method, and I worked this out:
IMongoCollection<TModel> collection = // ...
IFindFluent<TModel, TModel> findFluent = collection.Find(x => x.Id == id);
findFluent = findFluent.Limit(1);
TModel result = await findFluent.FirstOrDefaultAsync();
return result;
As it turns out, this too works, great!
I'm sure that there's some important reason that we have two different ways to achieve these results. What is the difference between these methodologies, and why should I choose one over the other?
async
keyword lets the compiler "manage" your code via its scheduler. This can but won't always make your app multi-threaded. Theawait
keyword signals to the compiler good points to decide and switch context or utilize a new thread. – whoisj Jun 4 '15 at 21:02async
specifically does not make your app multithreaded. See here. This isn't a question about C#, but the differences in methods available from the MongoDB C# API. – object88 Jun 4 '15 at 21:46FindAsync
won't make your app multi-threaded? There's a good chance it will do that if you don'tawait
right away. – John Saunders Jun 5 '15 at 1:22async
andawait
will explicitly not create threads. It does not create a background thread, nor does it put a thread to sleep. The whole point ofasync
andawait
is to relinquish control of a thread such that an message loop can process another queued up message on the same thread. If what you areawait
ing does not itself run on another thread or perform a background request intrinsically, addingawait
will not cause it to. The anti-example for usingawait
is a CPU-bound function. – object88 Jun 5 '15 at 12:58