Reputation: 125
I'm starting with Async MVC and I would like to know which is the main difference between this two implementations of an AsyncController.
The first one is using the ViewNameAsync and ViewNameCompleted implementation:
public class HomeController : AsyncController
{
// ... Manager declaration ...
public void IndexAsync()
{
AsyncManager.OutstandingOperations.Increment();
Manager.ExpensiveOperationCompleted += () =>
{
Debug.WriteLine("Expensive operation completed.");
AsyncManager.OutstandingOperations.Decrement();
};
Manager.ExpensiveOperationAsync();
}
public ActionResult IndexCompleted()
{
return View();
}
}
And the second one is using async-await implementation:
public class HomeController : Controller
{
// ... Manager declaration ...
public async Task<ActionResult> Index()
{
await Manager.ExpensiveOperation();
return View();
}
}
Upvotes: 0
Views: 119
Reputation: 1825
The main reason you do it this way (await the same line) is to tell the thread resource manager that it can balance the thread with other threads. This will allow other threads with higher priority to finish. You can also reference your expensive operation as a variable and then later down the code block, await it there. This will allow your expensive operation to do it's thing while the rest of the code executes. Basically like using Thread.Join.
Using a completed event isn't going to work in this case, considering your IndexAsync will return before your expensive operation completes and may cause undesired results if a recycle happens.
Upvotes: 0
Reputation: 456977
The "main difference" is that the Async
/Completed
approach is using an outdated and less maintainable way to do asynchronous request handling.
Upvotes: 2