簡體   English   中英

異步/等待和多層Web應用程序

[英]Async/Await and multi-layer web application

由於一些優化問題,我決定將控制器的操作方法重寫為異步方法。 它是一個多層應用程序,因此,我面臨一個體系結構問題,我想知道下面將顯示的兩個方法之間的主要區別是什么。 假設我的同步方法是:

public virtual ActionResult Method()
{
   SomeLogic.LargeOperation();
   return View(...);
}

LargeOpertation做很多事情。 這是偽代碼:

public void LargeOpertion() {
   DatabaseManipulations1();
   IndependentWork();
   CallingToWebService1();
   IndependentWork();    
   DatabaseManipulations2();
   IndependentWork();
   CallingToWebService2();
   IndependentWork(); 
}

LargeOperations內部的每個方法內部都有幾個方法,依此類推……問題是:我是否需要使它們全部異步並在幾乎每個應用程序層中使用await?

public virtual Task<ActionResult> Method()
{
   await SomeLogic.LargeOperation();
   return View(...);
}

public async Task LargeOpertion() {
   await DatabaseManipulations1();
   IndependentWork();
   await CallingToWebService1();
   IndependentWork();    
   await DatabaseManipulations2();
   IndependentWork();
   await CallingToWebService2();
   IndependentWork(); 
}

或者我可以像這樣在LargeOpertaion上使用任務:

public virtual Task<ActionResult> Method()
{
   await Task.Run(() => SomeLogic.LargeOperation());
   return View(...);
}

我們還假設IndependentWork()不太大。

由於一些優化問題,我決定將控制器的操作方法重寫為異步方法。

在開始之前,您應該意識到async將為您帶來什么,而不會給您帶來什么

異步操作不會更快地運行。 因此,對數據庫的異步調用不會比對數據庫的同步調用更快。

await不會盡早返回瀏覽器。 它所做的只是將當前線程釋放回ASP.NET線程池。

因此,每個單獨的請求仍會花費相同的總時間(實際上,只是稍長一些 ,但不是可檢測的時間)。

async 可伸縮性的幫助在於可伸縮性,即應用程序使用相同資源處理更多請求的能力。 然而,它不僅可以幫助你的web應用程序的可擴展性-它不能達到神奇到你的數據庫,並作出這樣的規模。 因此,如果您的可伸縮性瓶頸是數據庫而不是ASP.NET(通常是這種情況),那么async將完全無法幫助您。

如果你的數據庫后端是可擴展的(例如,NoSQL的,Azure的SQL或數據庫集群), 如果你的ASP.NET應用程序需要擴大規模,那么你就可以受益於async

我是否需要使它們全部異步並在幾乎每個應用程序層中使用await?

最好的方法是從“葉子”(最低層的方法)開始,然后從那里開始。 在這種情況下,請從數據庫交互開始,然后將其首先轉換為async

但是,絕對不要使用Task.RunTask.Factory.StartNew 相反,請使用真正的異步API,例如EF6中的async支持。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM