If I just return a view, is there performance diffrence to return it from Task?
[HttpGet]
public Task<ViewResult> Index()
{
return Task.FromResult(View());
}
[HttpGet]
public ViewResult Index()
{
return View();
}
In your case, the Task
version is likely to be slower, because you're just adding overhead of Task
with no benefit. Returning a Task
makes sense when you can take advantage of async
-await
, that is, if you're actually performing some action that can be made asynchronous in your method.
Asynchronous action won’t perform any faster than a standard synchronous action; it just allows for more efficient use of server resources. One of the greatest benefits of asynchronous code can be seen when an action wants to perform several asynchronous operations at a time.
this info from book that is named Professional ASP.NET MVC 4
Also there is an example about this topic
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);
}
}
Note that the calls are performed sequentially, so the time required to respond to the user is equal to the sum of the times required to make each individual call. If the calls are 200, 300, and 400 milliseconds (ms), then the total action execution time is 900 ms (plus some insignifi cant overhead).
Similarly, an asynchronous version of that action would take the following form:
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);
}
}
Note that the operations are all kicked off in parallel, so the time required to respond to the user is equal to the longest individual call time. If the calls are 200, 300, and 400 ms, then the total action execution time is 400 ms (plus some insignifi cant overhead).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With