ビューを返すだけの場合、タスクから返すためのパフォーマンスの違いはありますか?
[HttpGet]
public Task<ViewResult> Index()
{
return Task.FromResult(View());
}
[HttpGet]
public ViewResult Index()
{
return View();
}
ビューを返すだけの場合、タスクから返すためのパフォーマンスの違いはありますか?
[HttpGet]
public Task<ViewResult> Index()
{
return Task.FromResult(View());
}
[HttpGet]
public ViewResult Index()
{
return View();
}
あなたの場合、オーバーヘッドを追加するだけで何のメリットもないTask
ため、バージョンが遅くなる可能性があります。-を利用できる場合、つまり、メソッドで非同期にすることができるアクションを実際に実行している場合は、Task
aを返すことTask
は理にかなっています。async
await
非同期アクションは、標準の同期アクションよりも高速に実行されません。サーバーリソースをより効率的に使用できるようにするだけです。非同期コードの最大の利点の1つは、アクションが一度に複数の非同期操作を実行する場合に見られます。
名前の付いた本からのこの情報Professional ASP.NET MVC 4
このトピックに関する例もあります
public class PortalController : Controller {
public ActionResult Index(string city) {
NewsService newsService = new NewsService();
WeatherService weatherService = new WeatherService();
SportsService sportsService = new SportsService();
PortalViewModel model = new PortalViewModel {
News = newsService.GetNews(city),
Weather = weatherService.GetWeather(city),
Sports = sportsService.GetScores(city)
};
return View(model);
}
}
呼び出しは順番に実行されるため、ユーザーに応答するために必要な時間は、個々の呼び出しを行うために必要な時間の合計に等しいことに注意してください。呼び出しが200、300、および400ミリ秒(ms)の場合、アクションの合計実行時間は900 msです(それに加えて、わずかなオーバーヘッドもあります)。
同様に、そのアクションの非同期バージョンは次の形式を取ります。
public class PortalController : Controller {
public async Task<ActionResult> Index(string city) {
NewsService newsService = new NewsService();
WeatherService weatherService = new WeatherService();
SportsService sportsService = new SportsService();
var newsTask = newsService.GetNewsAsync(city);
var weatherTask = weatherService.GetWeatherAsync(city);
var sportsTask = sportsService.GetScoresAsync(city);
await Task.WhenAll(newsTask, weatherTask, sportsTask);
PortalViewModel model = new PortalViewModel {
News = newsTask.Result,
Weather = weatherTask.Result,
Sports = sportsTask.Result
};
return View(model);
}
}
操作はすべて並行して開始されるため、ユーザーに応答するために必要な時間は、個々の最長の呼び出し時間に等しいことに注意してください。呼び出しが200、300、および400ミリ秒の場合、アクションの合計実行時間は400ミリ秒になります(それに加えて、わずかなオーバーヘッドもあります)。