I am writing a blazor server web application.
This application works with a database and Entity Framework.
Here is a method i've wrote:
private void MyMethod()
{
var query = mydbcontext.mytable1.Where(t => ...);
foreach (var item in query)
{
...
}
}
As you can see this method is not declared with "async Task". So she will be called without "await" keyword.
I can declare it with "async Task" and call it with "await". It works but it gives me a warning because i have no async call inside.
Let's suppose i decide to not declare it with "async Task" in order to avoid the warning.
What will happen if i need to change something in my function later which needs an Async call (For example this):
private async Task MyMethod()
{
var query = mydbcontext.mytable1.Where(t => ...);
foreach (var item in query)
{
...
}
var countresult = await query.CountAsync();
}
I will need to search all calls of MyMethod and add "await" on each of this calls.
To prevent that, I am wondering if i should not declare all my methods with "async Task". But this is ugly because i will get warnings.
What is the best practice ?
And is there a way to do this loop as ASync ?
private async Task MyMethod()
{
var query = mydbcontext.mytable1.Where(t => ...);
await foreachAsync (var item in query)
{
...
}
var countresult = await query.CountAsync();
}
Thanks
What will happen if i need to change something in my function later which needs an Async call (For example this)- then you change your method to async. other options: 1) ignore the warning or 2) make it just aTask(not async), if you want it to already be awaitable.asyncmethods from the front back, but if something from the back requiresasyncthen you work that in from the back to the front, if that makes sense. There is some overhead to making your methodasync, the compiler essentially builds a whole state machine around your method. You are getting those warnings for a reason.await mydbcontext.mytable1.Where(t => ...).ToListAsync()anyways. because theforeachmay be doing an internal non-asyncToListbut I don't know this for a fact.await foreachin C# 8 but it requires anIAsyncEnumerableinstead of the normalIEnumerable, which I am not sure ifIQueryablesuse yet. learn.microsoft.com/en-us/archive/msdn-magazine/2019/november/….Where(), you are not executing it yet. That happens when you foreach over it. And again when you do a CountAsync (or plain Count)