Feature Post


ASP.NET: Async calls vs threading

This answers following questions:

  • How to improve performance?
  • Should I ever use Threading in ASP.NET?

How to improve performance of an ASP.NET MVC page that calls a database which takes a specific amount of time, and the results are then rendered on to an html page? This means, for instance, if 4 method calls takes 4 seconds, then target is, to improve the performance to 2 seconds for 4 database calls.

   1: string strReturnValue1 = CallDB("SomeStoredProcedureThatTakes1CompleteSecondToProcess1");
   2: string strReturnValue2 = CallDB("SomeStoredProcedureThatTakes1CompleteSecondToProcess2");
   3: string strReturnValue1 = CallDB("SomeStoredProcedureThatTakes1CompleteSecondToProcess1");

Takes exactly 3 seconds.

Move it inside a web service, and then call:

   1: yourWebServiceObject.CallDB +=  new CallDBCompletedEventHandler(CallDBCompleted); 

Define a handler:

   1: void CallDBCompletedEventHandler(object sender, CallDBCompletedEventArgs e)
   2: {
   3:     SomeLabel.Text += string.Format("Return value: [{0}]<br/>", e.Result);
   4: }

Lets call it async'ly:

   1: yourWebServiceObject.CallDBAsync("SomeStoredProcedureThatTakes1CompleteSecondToProcess2");
   2: yourWebServiceObject.CallDBAsync("SomeStoredProcedureThatTakes1CompleteSecondToProcess2");
   3: yourWebServiceObject.CallDBAsync("SomeStoredProcedureThatTakes1CompleteSecondToProcess2");

Takes ~1 second.

How so?

The I/O thread(completion ports or IOCPs) use the ThreadPool, but they use IOCP, which do not interfere with ASP.NET requests. Therefore, you can safely use the asynchronous call to a web service, and update the page accordingly; for instance using UpdatePanel.


These web service asynchronous calls, uses IOCP behind the scenes, freeing ASP from essentially all of the burdens.

I could have done it using the thread pool as well?!

Usually, unless we want to parallelize a CPU-intensive operation in order to get it done faster, it is generally *not recommended* to use a worker thread; this eventually will starve the ThreadPool in an ASP.NET process by queuing too many work items.

Don't forget that you also use Reactive Framework in your ASP.NET app to do the job async'ly.

For instance,

   1: var o = Observable.Start(() => { CallDB 
   3: ("SomeStoredProcedureThatTakes1CompleteSecondToProcess2"); Popup.Message("Done."); Popup.Show (); });
   4: o.First();   // subscribe and wait for completion of background operation

Takes ~1 second.

This and this a very interesting article targeted to performance as well as scalability gains in a web app.