Your ASP.NET application performs slower than expected? How many times do you access your database for each request? Did you use SQL Profiler to find out? Did you know that chatty database access is one of the most common performance sins (this is my own observation)?
Want to improve? - Reduce the number of database queries.
Not an option? - You may want using multithreading. Proceed with caution.
Real world scenario
You need to run 3 independent heavy database queries – Q1, Q2, Q3. You need to use the result from the three – Result = Q1+Q2+Q3. You never know the order in which each query completes. It can be: Q1Q2Q3, Q1Q3Q2, Q2Q3Q1, Q2Q1Q3, Q3Q2Q1, Q3Q1Q2. Missed any combination? Run one after another would create significant latency. Running each on its own thread would create latency of Max(Q1,Q2,Q3) which is less that sum of the three.
How to run each query on its own thread and wait for the completion for each one?
Using Thread object
The following code spawns three threads and waits for all to join, and then use the results from each.
See any issues using it in ASP.NET? One caveat though, creating threads manually like this may cause performance hit as it involves context switching – CPU consuming operation. Consider using ThreadPool object.
Using ThreadPool object (preferred, but are you using COM?)
ThreadPool is preferred as it already has live threads allocated for you. No need to ask for a favor from CPU in the moment of truth. Here is the code:
If your function calls on COM object – avoid using ThreadPool, its Apartment model is not compatible with COM and it cannot be changed. More info - Pitfalls With .Net Multithreading And COM Objects – Threads Must Have Compatible Apartment Models (MTA vs. STA).
Another point to call out is that performance improvements based on multithreading is subject to amount of available CPU’s. Test your solution first!
This post was written with help from Lior, MCS Israel Architect.
Download sample project with the code from my SkyDrive: