If you are using async/await at a lower level in your architecture, is it necessary to "bubble up" the async/await calls all the way up, is it inefficient since you are basically creating a new thread for each layer (asynchronously calling an asynchronous function for each layer, or does it not really matter and is just dependent on your preference?
This question suggests a couple of areas of misunderstanding.
Firstly, you don't create a new thread each time you call an asynchronous function.
Secondly, you don't need to declare an async method, just because you're calling an asynchronous function. If you're happy with the task that's already being returned, just return that from a method which doesn't have the async modifier:
public class EntityRepository<E> : IRepository<E> where E : class
{
public virtual Task Save()
{
return context.SaveChangesAsync();
}
}
public abstract class ApplicationBCBase<E> : IEntityBC<E>
{
public virtual Task Save()
{
return repository.Save();
}
}
This will be slightly more efficient, as it doesn't involve a state machine being created for very little reason - but more importantly, it's simpler.
Any async method where you have a single await
expression awaiting a Task
or Task<T>
, right at the end of the method with no further processing, would be better off being written without using async/await. So this:
public async Task<string> Foo()
{
var bar = new Bar();
bar.Baz();
return await bar.Quux();
}
is better written as:
public Task<string> Foo()
{
var bar = new Bar();
bar.Baz();
return bar.Quux();
}
(In theory there's a very slight difference in the tasks being created and therefore what callers could add continuations to, but in the vast majority of cases, you won't notice any difference.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…