Async Controllers ( Thank you .net 4.5 )

Async controllers are basically normal controllers but for long running processes that can take time to complete ( Web Services , IO operations , Report Generation , etc )

so instead of using normal controllers that block the execution and may block the web server we usually use Async controllers

So how is that is done before and what is new in Asp.Net MVC 4.5

Old Way 

https://github.com/waelemara/async-controllers/tree/master/Before

New Way

https://github.com/waelemara/async-controllers/tree/master/New

I will focus on the new way here , in .net 4.5 we can use the ( async , await ) new keywords to tell the compiler , well we have an async method being called , this applies to actions so we can mark the action to be and async and instead of breaking the logic into two methods ( that looks ugly and breaks the logical sequence of the code ) to the normal action method but we need to tell the compiler this is an async controller

so the normal code looks like this

public ActionResult Index()
        {
            var faceBookCount =  GetFacebookCommentCount(); // takes some time
            var commentCount = GetFacebookLikeCountAsync(); // takes some time
            var faceBookStatus = new FaceBookStatus()
                {
                    FaceBookCount = faceBookCount,
                    CommentCount = commentCount
                };
            return View(faceBookStatus);
        }
to be :
public async Task<ActionResult> Index()
        {
            var faceBookCount = await GetFacebookCommentCountAsync();
            var commentCount = await GetFacebookLikeCountAsync();
            var faceBookStatus = new FaceBookStatus()
                {
                    FaceBookCount = faceBookCount,
                    CommentCount = commentCount
                };
            return View(faceBookStatus);
        }
so this makes the application pool release the thread that is handling your request and then assign another one to handle the request after the function marked with await finished work so the web server does not get blocked
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s