Reputation: 3407
I am new to ASP.NET MVC (using 4) and have some basic questions regarding multi-threading.
Right now I have written all the controllers. Should I explicitly create a thread poll and assign a thread to each incoming request? I read something suggesting that this multi-threading is done automatically in MVC, and I shouldn't do my own. Is this true?
Most requests would change the database (i.e. upload a file). This post says DbContext
is not thread safe, and the chosen answer is to create a new instance for each thread, which I did in my controller. Does this make it safe if MVC automatically creates threads (question #1)?
Thanks!
Upvotes: 3
Views: 2699
Reputation: 1977
1) You don't have to worry about it.
On the Web server, the .NET Framework maintains a pool of threads that are used to service ASP.NET requests. When a request arrives, a thread from the pool is dispatched to process that request. If the request is processed synchronously, the thread that processes the request is blocked while the request is being processed, and that thread cannot service another request.
From here: http://msdn.microsoft.com/en-us/library/ee728598(v=vs.100).aspx
2) You should be fine if you're constructing a DbContext
for each request - doing this in your Controller's Constructor will do this for you. (You can also look into an Inversion of Control/Dependency Injection framework if you want, but it doesn't change the principle.)
Upvotes: 4