Reputation: 1320
Still kind of new to C#. My code gives me the results I want, but I'm uncertain if I did implemented it in an OK way. Please elaborate if you feel like answering.
My goal was to search for entries in my MongoDB via FindAsync
. Here is my code for that:
public async Task<List<T>> SearchDocAsync<T, U>(string collection,
string findFieldName, U findValue)
{
var _collection = db.GetCollection<T>(collection);
var filter = Builders<T>.Filter.Eq(findFieldName, findValue);
var result = await (_collection.FindAsync(filter).Result.ToListAsync());
return result;
}
And here is the way I call it in WinForms:
private async void BtnReadAll_Click(object sender, EventArgs e)
{
var asyncResults = await myMongoAux.SearchDocAsync<MyTModel, string>(
myCollectionName, "MyDBString", "TestString");
foreach (var r in asyncResults)
{
RtxbxResult.Text += $"{r.MyDBInt}\t{r.MyDBString}\n";
}
}
Is this safe? Shouldn't I be using a using
(but how)? And I have read something about that you should use:
ConfigureAwait(false)
How and why?
Be so kind and help me out understand more. Thank you for your time. :)
Upvotes: 0
Views: 8572
Reputation: 14846
You can't use ConfigureAwait(false)
on that method because you need to be back to the captured synchronization context (UI thread) after the await
.
Upvotes: 3
Reputation: 36401
this looks odd
var result = await (_collection.FindAsync(filter).Result.ToListAsync());
It should probably be
var result = await ((await _collection.FindAsync(filter)).ToListAsync());
Using .Result
for tasks will block until the task has completed. Due to the way threads work in UI applications this has a rather high chance of causing a deadlock. So it is recommended to avoid .Result
and .Wait()
unless you are sure that no deadlock can occur.
Upvotes: 6