Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does async in the data layer require the entire call stack to be async as well?

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?

like image 813
Roger Avatar asked Jan 23 '17 21:01

Roger


People also ask

What happens when you call an async method?

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.

How does async await work internally?

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.

What is async stack?

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.

What happens during async await?

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.


1 Answers

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.

like image 159
Stephen Cleary Avatar answered Sep 18 '22 18:09

Stephen Cleary