Reputation: 40393
I have an MVC3 project with .NET 4.5 (we can't upgrade to MVC4 for various reasons). I have a need to run three database queries, each of which takes a couple seconds, to populate three sets of data in an AJAX request.
My initial thought was to just make 3 separate AJAX calls, but I ran into issues with maximum concurrent AJAX requests - we have a lot of other AJAX calls going on at the same time, so these 3 were blocked on the client while waiting for all the calls to clear.
So I'm trying to put it in a single AJAX call, but I still want to execute the three queries simultaneously.
Since it's MVC3, I apparently can't do the simple async Task<JsonResult>
with await Task.WhenAll(tasks)
on three tasks.
I haven't done a lot of multi-threading other than simple "fire-and-forget" stuff, so I want to make sure I'm doing this right.
The following simple way works properly, but I'm pretty sure it's not the right way - I've read a lot of people talking about how ASP.NET is picky about thread handling, especially as you start to use a lot of threads.
var threads = new List<Thread>();
threads.Add(new Thread(() => x1 = Method1()));
threads.Add(new Thread(() => x2 = Method2()));
threads.Add(new Thread(() => x3 = Method3()));
threads.ForEach(t => t.Start());
threads.ForEach(t => t.Join());
// x1, x2, and x3 are now populated
What do I need to change in order to properly use the ThreadPool or whatever other threading techniques I should be considering, and make sure I close things properly? The site generally has only a few dozen concurrent users, and this call would be made whenever they load up a page - so it's not a huge number of threads.
I'll also add exception handling to make sure nothing blows up.
Upvotes: 3
Views: 378
Reputation: 54618
What do I need to change in order to properly use the ThreadPool or whatever other threading techniques I should be considering, and make sure I close things properly?
It depends.
Your current code won't reuse a thread from the thread pool and possibly thread-starve the PoolThread causing a 500 (ASP.Net request processing stalled because the CLR thread pool is out of threads). There is a small performance penalty for bringing up a new thread (which is why the thread pool exists in the first place), but for high through-output high concurrency websites, this is a good choice.
That being said, if your website is servicing a low through-output low concurrent user base, it's over kill in my opinion. It's much easier on the eyes (opinion) to use the Task.Factory
. This will use thread in the thread pool, but unless you're running the website on a single-core machine, I doubt anyone will notice.
Outside of the threading models, there are much more architectural ways to reduce database hits, but your question is so specific, there isn't much I could suggest without knowing more.
Upvotes: 2