Deserialized The Ramblings of a Web Architect

16Jul/111

Call mulitple services or methods asynchronously in ASP.NET MVC controller

I recently had to write some code that reached out to both Google and Bing, performed searches on both, combined and manipulated the results and return the result to the client via JSON.

My problem was that sometimes either of those two services could be slow and there is a possibility that I may need to add additional data sources at a later time.  The code originally looked like this:

 

old-code

 

As you can see, this code would accomplish the goal without a hitch, however if Google took longer than usual, Bing would have to wait for Google to finish.  This just creates a bad experience for my users.   I needed a way to be able to fire off both of those searches at the same time without blocking one another, however to be of any use to my users, the action would have to wait for both of them to complete before combining the results and return them to the client.  This problem would be amplified by adding additional data services (like Yahoo, for example).

Even though I had done this several times in PHP, I had no idea how to accomplish it in C#.  I know that AsyncControllers exist and it sounds like they rock, but what if I wanted to keep this all in the same controller as other related code?

I did some digging and found nothing, so I turned to a developers best friend – StackOverflow.  I posted a question asking how to accomplish this and got back a few great answers.

This is what I decided on, and it works great:

new-code

You can create as many Task’s as you need, and then start each of them with the Start() method.  Then using the Task.WaitAll() method, you instruct your program to wait until all of those Task’s have completed before continuing to the next line of code.

You can also specify a timeout as the second parameter of Task.WaitAll that will prevent your Task’s from running indefinitely, which is definitely helpful for Ajax requests when the client is waiting on some response.

Comments (1) Trackbacks (0)
  1. If you are not careful about what you do, then you can easily start method hopping and getting nowhere.


Leave a comment

(required)

No trackbacks yet.