Sample code. In the async method below, could the IndexAsync method actually return before the corresponding Get* methods finish? Im trying to understand the basics of async and await, much like the author mentions he was also doing.
Credit to author for code: https://www.exceptionnotfound.net/using-async-and-await-in-asp-net-what-do-these-keywords-mean/
So, based on my understanding now, is the following true:
The benefit of the Async method is that when the execution comes to the calls of the Get* methods, they dont have to wait, so the code that follows can execute and when the Get* methods finally return their values, then the IndexAsync can finally return. That about sum it up?
public class ContentManagement
{
public string GetContent()
{
Thread.Sleep(2000);
return "content";
}
public int GetCount()
{
Thread.Sleep(5000);
return 4;
}
public string GetName()
{
Thread.Sleep(3000);
return "Matthew";
}
public async Task<string> GetContentAsync()
{
await Task.Delay(2000);
return "content";
}
public async Task<int> GetCountAsync()
{
await Task.Delay(5000);
return 4;
}
public async Task<string> GetNameAsync()
{
await Task.Delay(3000);
return "Matthew";
}
}
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
Stopwatch watch = new Stopwatch();
watch.Start();
ContentManagement service = new ContentManagement();
var content = service.GetContent();
var count = service.GetCount();
var name = service.GetName();
watch.Stop();
ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;
return View();
}
[HttpGet]
public async Task<ActionResult> IndexAsync()
{
Stopwatch watch = new Stopwatch();
watch.Start();
ContentManagement service = new ContentManagement();
var contentTask = service.GetContentAsync();
var countTask = service.GetCountAsync();
var nameTask = service.GetNameAsync();
var content = await contentTask;
var count = await countTask;
var name = await nameTask;
watch.Stop();
ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;
return View("Index");
}
}