I am trying to understand the async/await mechanism with MVC. Now I do not consider a use case where I would go out of the "normal flow" (using either full sync or full async end-to-end). I just want to make sure to understand the why it doesn't work here.
When "SyncMethod" is called it hangs indefinitely and never returns.
When "AsyncMethod" is called it returns a view quickly without hanging.
When "TaskMethod" is called it returns a view quickly without hanging as well.
I am not exactly sure to understand why when a synchronous method calls an async method it is impossible to return a result.
What am I missing here?
using System;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace MvcAsyncAwaitTest.Controllers
{
public class HomeController : Controller
{
/// <summary>
/// Synchronous method running async method as sync
/// Hangs at Hello().Result, never returns
/// </summary>
/// <returns></returns>
public ActionResult SyncMethod()
{
ViewBag.Message = Hello().Result;
return View();
}
/// <summary>
/// Asynchronous method awaiting asynchronous method
/// Do not hang
/// </summary>
/// <returns></returns>
public async Task<ActionResult> AsyncMethod()
{
ViewBag.Message = await Hello();
return View("Index");
}
/// <summary>
/// Synchronous method running a task based method synchronously
/// Returns a valid result
/// </summary>
/// <returns></returns>
public ActionResult TaskMethod()
{
ViewBag.Message = Hello2().Result;
return View("index");
}
private async Task<string> Hello()
{
return await HelloImpl();
}
private Task<string> Hello2()
{
return Task.Run(() => "Hello world 2");
}
private async Task<String> HelloImpl()
{
return await Task.Run(() => "Hello World");
}
}
}