These days it is common for the data layer to interact asynchronously with the DB:
public async Task<Customer> GetCustomer(int id)
{
using (db = new AppDbContext())
{
return await db.Customers.FindAsync(id);
}
}
With this technique, it is my understanding that all calling methods, all the way to the UI layer, then must also be defined with the async keyword. Thus you end up with an application where every method or function that eventually interacts with the DB be an async method.
This seems terribly messy and "pollutes" all the application layers with knowledge of an implementation detail inside the data layer.
Am I misunderstanding something or is this simply what one has to do?
The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.
An async function can contain an await expression, that pauses the execution of the function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value. You can think of a Promise in JavaScript as the equivalent of Java's Future or C# 's Task.
Asynchronous stack traces allow you to inspect function calls beyond the current event loop. This is particularly useful because you can examine the scope of previously executed frames that are no longer on the event loop. This feature is currently an experiment and needs to be enabled.
The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete.
Am I misunderstanding something or is this simply what one has to do?
No, you're right. It's just something you have to do.
This seems terribly messy and "pollutes" all the application layers with knowledge of an implementation detail inside the data layer.
Yes, those implementation details do leak, and this is unfortunate. It's just the reality of how the vast majority of computer languages work.
I tend to compare the async
details to the IDisposable
details. If one class implements IDisposable
, then its containing (owning) classes should, etc., etc. But whether a class owns resources should really be an implementation detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With