[英]How should i use async await between my business/service/application layer
Right now my methods look something like this. 现在,我的方法看起来像这样。
ProductManager class in business 业务中的ProductManager类
public static async Task<List<ProductItem>> GetAllProducts()
{
var context = GetMyContext();
return await context.Products.select(x =>
new ProductItem{ //create item})
.ToListAsync();
}
ProductService class in service. 服务中的ProductService类。
public async Task<List<ProductItem>> GetAllProducts()
{
return await ProductManager.GetAllProducts();
}
ProductController in application. 应用中的ProductController。
public async Task<ActionResult> Index()
{
var ps = new ProductService();
var productsAsync = ps.GetAllProducts();
// Do other work.
var products = await productsAsync;
return View(products);
}
This application gets high usage, Is this way of doing it totally wrong ? 此应用程序使用率很高,这样做是完全错误的吗? Should I be await every method ?
我应该等待每种方法吗? Will this start a new thread every time await is called ?
每次等待时都会启动一个新线程吗?
This application gets high usage, Is this way of doing it totally wrong?
此应用程序使用率很高,这样做是完全错误的吗?
No; 没有; it looks good to me.
对我来说看起来不错。
Should I be await every method?
我应该等待每种方法吗?
Yes. 是。 Once you put in the first
await
(in ProductManager
), then its callers should be await
ed, and their callers await
ed, and so on, up to the controller action method. 一旦你把第一
await
(在ProductManager
),那么它的调用者应该await
ED,他们的来电者await
编,依此类推,直至控制器的操作方法。 This "growth" of async
is entirely natural; 这种
async
“增长”是完全自然的。 it's called " async all the way " in my MSDN article on async best practices. 在我关于异步最佳实践的MSDN文章中,它被称为“ 一路异步 ”。
Will this start a new thread every time await is called?
每次等待时都会启动一个新线程吗?
No. Await
is about freeing up threads, not using more threads. 不。
Await
是关于释放线程,而不是使用更多线程。 I have an async
intro on my blog that describes how async
and await
work. 我的博客上有一个
async
介绍 ,介绍了async
和await
工作方式。
await
simply awaits for something to complete. await
只是等待某件事完成。 If you don't need the results of a task in your method, you don't need to await it. 如果您的方法不需要任务的结果,则无需等待它。
GetAllProducts
should simply return the results of ToListAsync
. GetAllProducts
应该只返回ToListAsync
的结果。
public static Task<List<ProductItem>> GetAllProducts()
{
var context = GetMyContext();
return context.Products
.Select(x => new ProductItem{ //create item})
.ToListAsync();
}
async/await
adds a bit of overhead, since the compiler has to generate a state machine that stores the original synchronization context, waits for the awaited task to finish and then restores the original synchronization context. async/await
增加了一些开销,因为编译器必须生成一个存储原始同步上下文的状态机,等待所等待的任务完成,然后恢复原始同步上下文。
Adding async/await
on a method that doesn't need to process the result of the task simply adds overhead. 在不需要处理任务结果的方法上添加
async/await
只会增加开销。 In fact, there are some Roslyn analyzers that detect and fix this issue 实际上,有一些罗斯林分析仪可以检测并解决此问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.